Question

May I ask what is wrong with my code? strcpy seems to be working only inside the function. But when I'm passing it to another function, the first array prints okay but the other ones don't print correctly?

What seems to be the problem with my code and what is the correct way?

Here is the code:

void copyString(char *data, int ctr){
   int i;
   char constData[10][50] = {{"Hello"}, {"Goodbye"}, {"Konichiwa"}, {"Sayonara"},
                             {"Ni Hao"}, {"Zai Jian"}, {"Annyeong Haseyo"},
                             {"Annyeonghi Gaseyo"}, {"Bonjour"}, {"Au Revoir"}};
   char temp[50][100];

   strcpy(temp[ctr], constData[ctr]);

   if (ctr == 4)
      for(i = 0; i <=ctr; i++)
          printf("In function: %s\n", temp[i]); 

   strcpy(&data[ctr], temp[ctr]);
}

int main() {
   int i = 0, ctr = 0;
   char data[20][10];

   for (ctr = 0; ctr <= 4; ctr++)
       copyString(data[ctr], ctr);

   printf("\n");
   for(i = 0; i <= 4; i++)
         printf("%s\n", data[i]);

   return 0;
}

The output gave me this:

In function: Hello
In function: Goodbye
In function: Konichiwa
In function: Sayonara
In function: Ni Hao

Hello


a
a

But the output should be like this:

In function: Hello
In function: Goodbye
In function: Konichiwa
In function: Sayonara
In function: Ni Hao

Hello
Goodbye
Konichiwa
Sayonara
Ni Hao

Thank you in advance!

Was it helpful?

Solution

Here is your culprit:


strcpy(&data[ctr], temp[ctr]);

This should be:


strcpy(data, temp[ctr]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top