简体   繁体   中英

substitute string character with a character from another string in C language

when i run this program, it crashes. I would like to copy one char from one string to another. Can you help me? ex: I would like to have "wello" as array[0] instead of "hello"

int main()
{
    int N=3;
    char *array[10];
    array[10]=malloc(N*sizeof(char));
    array[0]="hello";
    array[1]="wall";
    array[2]="dinner";
    array[0][0]=array[1][0];
    printf("array[0][0]: %c\n", array[0][0]);
    printf("array[0]= %s, array[1]= %s, array[2]= %s", array[0], array[1], array[2]);
    return 0;
}

You've got a few problems here:

  1. array has only 10 elements, and hence none with index 10 .
  2. You didn't allocate the space for the strings you assign into the first 3 elements of array , so may not be allowed to modify them.
  3. Why does array have 10 elements if you only use 3? Why are you allocating space for the 11th if you never use it?

None of your character pointers in your array point to valid memory locations. You need to do a malloc for each pointer to store a string in it. Also, array[10] is outside of the index you've declared for array (which is 0 to 9).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM