Home > Mobile >  Array of Strings to functions and use strcpy
Array of Strings to functions and use strcpy

Time:10-01

So basically, what I'm trying to do:

I have an array of n strings. ("n" is generated through code, not before known)

The real input is a giant string that I will splice, and add the parts to each position of the array.

In the example I've simulated a sentence with n=3 , but "n" can be any number.

void addWords(char *array[][300], int n) {
    char p[] = "Hello ";
    char p1[] = "World ";
    char p2[] = "!";

    strcpy(array[0],p);
    strcpy(array[1],p1);
    strcpy(array[2],p2);

    printf("%s%s%s\n",array[0],array[1],array[2]);

}


int main(int argc, char const *argv[])
{
    int n = 3;
    char array[n][300];

    addWords(array,3);

    return 0;
}

The code gives segmentation fault!! =(((( Tried to research, but wasn't able to fix it.

CodePudding user response:

//void addWords(char *array[][300], int n) {
void addWords(char array[][300], int n) { // <== use `char array[][300]`
    char p[] = "Hello ";
    char p1[] = "World ";
    char p2[] = "!";

    strcpy(array[0],p);
    strcpy(array[1],p1);
    strcpy(array[2],p2);

    //printf("%s%s%s\n",p[0],p[1],p[2]);
    printf("%s%s%s\n",array[0],array[1],array[2]); // <== I think you meant `array` instead of `p`
}

CodePudding user response:

This

void addWords(char *array[][300],
              ^^^^^^^^^^^^^^^^^^

means

pass a pointer to an array containing 300 char pointers

What you want to say is

pass a pointer to an array containing 300 char

So all you need is:

void addWords(char *array[][300], --> void addWords(char array[][300],

CodePudding user response:

I see that you declared 'addWords' with argument of type "char *array[][300]", but pass value of type "char array[n][300]". Different types.

  •  Tags:  
  • c
  • Related