I have a 2d character array of the form arr[][]
. I need to add a single character to the end and sometimes to the beginning of the ith or jth row in this array. Here is the code snippet:
arr[j] = strcat(arr[j],")");
arr[i] = strcat("(",arr[i]);
When I compile the code, I get the error: incompatible types in assignment. Now I am assuming arr[j]
and arr[i]
are strings. Where am I going wrong? In other words, what is the best practice to append or add a character to the beginning of a string?
First of all, you cannot assign the char *
returned by strcat
to an existing array row.
But more importantly, strcat
does not allocate a new string with the result of the concatenation, but instead performs the concatenation inplace in the first string. The return value is always the first string and is just a convenience. So, in the first case you just have to do:
strcat(arr[j],")");
(assuming arr[j]
is big enough for the added character)
The second case is more complicated, since you have to add the )
to the beginning of an existing string. You can e.g. perform the operation in a separated buffer and then copy it back to arr[j]
using strcpy
, or move the whole content of the string one character forward and add the parenthesis manually:
memmove(arr[j]+1, arr[j], strlen(arr[j]));
arr[j][0]='(';
From your mistake I fear you think that char *
is like the string classes in other languages, but alas it's not like that. Remember, in C strings are just dumb arrays of characters, don't expect any fancy commodities as in higher-level languages.