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);