Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

Pl. see if the simple example below helps,

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(int argc, char* argv[])
{
    char myarray[2][10], *temp;

    //Populating something in the array
    strcpy(myarray[0], "string1");
    strcpy(myarray[1], "string2");
    printf("%s\n", myarray[0]);
    printf("%s\n", myarray[1]);

    //Adding something at the end of the string..
    //Be careful to check if the source is large enough.
    //Also consider using strncat
    strcat(myarray[0], ")");
    printf("Appended at the end %s\n", myarray[0]);

    //Append at the beginning
    //Here you can use a temporary storage.
    //And pl. do the required error handling for insufficent space.
    temp = malloc(strlen(myarray[1]) + strlen("(") +1);
    strcat(temp, "(");
    strcat(temp, myarray[1]);
    strcpy(myarray[1], temp);
    printf("Appended at the beginning  %s\n", myarray[1]);
    free(temp);
    return 0;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top