2

I want to save about 20 country names into one string and then copy them to another but it always do me some mistake, can anybody help me with it?

This is my code:

char array1[30][30], array2[30][30];

This is how i put them into first array:

fscanf(fr, "%s", array1[i]);

This all works but when i want to do:

array2[0] = array1[0];

I get error:

incompatible types when assigning to type 'char[30]' from type 'char *'

When I use:

strcpy(array2[pom2], array1[i]);

it shows no error but doesn't copy it nor print it out.

Alex Poole
  • 183,384
  • 11
  • 179
  • 318
Ricsie
  • 319
  • 5
  • 14

2 Answers2

1

For the first error : you cannot copy an array into another one. You can just copy salar values (chars, in your case).

If you want to copy a string into another, you indeed have to use the strcpy function (or a close relative, as strncpy. You should give us the full code so that we can see where the problem is with your call to strcpy.

Fabien
  • 12,486
  • 9
  • 44
  • 62
  • When i use `strcpy` it prints me something like this: !"#$%&'<>*+,-./ – Ricsie Nov 08 '12 at 19:33
  • Did you check that `fr` is actually valid ? i.e., did you check, while opening it, that everything was OK ? If something went wrong, `fr`is `NULL` and then anything can happen. – Fabien Nov 08 '12 at 19:41
  • yes i checked if its not `NULL` also checked array1[0] and printed it it prints: Croatia – Ricsie Nov 08 '12 at 19:45
1

Did you try passing character by character?

for( i = 0; i < 30; i++ ){
   for( j = 0; j < 30; j++ ){
      targetArray[ i ][ j ] = sourceArray[ i ][ j ];

      /* End of the string, stop copying */
      if ( sourceArray[ i ][ j ] == '\0' ){
         break;
      }
   }
}
Alberto Bonsanto
  • 17,556
  • 10
  • 64
  • 93
  • This is fast not deep thinking solution – Alberto Bonsanto Nov 08 '12 at 19:28
  • 1
    You will copy useless characters with this solution. And, that is generally slower than using `strcpy` or `memcpy`, which are usually optimized by compilers. – Fabien Nov 08 '12 at 19:31
  • @Fabien, that's correct that's why I said "fast and not thinking solution" – Alberto Bonsanto Nov 08 '12 at 19:42
  • if i use this i get about 20-30 weird chars like &@-:-/ and so on, it looks like i copy from bad source, but then i tried to print array1[0] it prints: Croatia then i tried to do `for (i = 0; i < 30; i++){array2[0][i] = array1[0][i] }` then when i print array1[o] i get Croatia and when i print array2[o] i get again these 30 weird characters – Ricsie Nov 08 '12 at 19:43
  • It somehow didnt worked for me, but deleted the whole project folder just copied the code to new project and tried the strcpy again and now it worked. Thanks a lot for helping me and so fast help, much appreciated!! – Ricsie Nov 08 '12 at 21:44