Why am I getting "array initializer must be an initializer list or string literal"?
I am completely new to C programming and the language I used to work on before C was Java. I am trying to get a method to return a char array and it is not working. Here is my syntax:
char * insertToArray(char * val){ int k; char arr[2] = val; // do some other staffs here to the value return arr; } int main(){ char s1[] = {"one", "two"}; char newArr[]; int i; for(i = 0; i < 2; i++){ newArr[] = insertToArray(s1[i]); } return 0; }
All I am trying to do is pass the s1
array to insertToArray
and do some kind of calculation on the values, then return a whole new single array. I am a complete beginner and I couldn't find any other help online. What am I doing wrong?
1 Answer
The rules of C says that you can't initialize an array using a pointer. Instead define the array then copy to it:
char arr[strlen(val) + 1]; // Make sure there's enough space strcpy(arr, val);
Then you can not define empty arrays. An array must have a size. And using the array newArr
in the main
function is wrong anyway since the function you call returns a pointer. So newArr
must be a pointer as well.
Now with that out of the way, there are a couple of other things in your (current) code that are very wrong.
The first being the size of the array arr
. An array of two characters can only hold space for one-character string. Remember that strings are null terminated, there must be space for the full string plus the terminator.
The second problem is that you return a pointer to a local variable. Once the function insertToArray
returns, all its local variables cease to exist. Having a pointer to one of those variables will lead to undefined behavior when you use it.
The fix to the first problem is shown above. The fix to the second problem is a little harder, and involves either passing an extra argument to the function or allocating memory dynamically. I recommend the extra argument way:
char * insertToArray(const char * val, char * arr){ strcpy(val, arr); // do some other staffs here to the value return arr; }
Then call it like
char newArr[strlen(s1[i]) + 1]; insertToArray(s1[i], newArr);
ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoa21rZWt%2Bc32OsJ%2ByZZGieqp5xp6rraGenHqivtGasGahnp7Bqq3LorGeql2iwrTAjJucZpmeYravtdOimKWhqpq%2FbrjIrKtmp6JiwLW%2ByKeeZqSZqbKzrQ%3D%3D