Hasan Saad
Hasan Saad

Reputation: 279

Multidimensional array acting strangely

#include <stdio.h>
#include <stdlib.h>
char number[5000]="37107287533902102798797998220837590246510135740250\
46376937677490009712648124896970078050417018260538\
.....more numbers.....";
char numbers[100][50];
main()
{
    int x,z;
    extern char numbers[100][50],number[5000];
    for(x=0;x<100;x++)
    {
        for(z=0;z<50;z++)
        {
            numbers[x][z]=number[50*x+z];
        }
    }
    printf("%s\n",numbers[0]);
}

So the thing is I have this code and for some reason numbers[0] is being the same as number. Isn't numbers[0] supposed to be the first 50 characters first.I can't figure this out.Thanks in advance.

Upvotes: 0

Views: 87

Answers (2)

torek
torek

Reputation: 490118

You are printing numbers[0] with a %s directive. This takes the address of the first char (i.e., a value of type char *) pointing to the first character of a "string": a sequence of chars terminated by a '\0'.

The numbers[0] array contains 50 non-'\0' chars, and immediately after that (at numbers[1]) there's another non-zero char. So %s has no idea where to stop. (Technically this causes undefined behavior when you run off the end of the first array into the second one, but in practice, C systems just keep going.)

Note that if you set all 50 chars to non-zero values, there is no room left for a '\0' byte. You'll need to set aside 51 chars to hold 50 printable chars and the one final '\0'. Alternatively, you can use a structure other than a C string, such as a counted-array (the things that memcpy and memcmp deal with), but unless you want to allow '\0' bytes in your char array, that's usually too much work.

Upvotes: 3

P0W
P0W

Reputation: 47854

for(x=0;x<100;x++)
    {
        for(z=0;z<50;z++)
        {
            numbers[x][z]=number[50*x+z];
        }
    numbers[x][z+1] ='\0'; //Did you miss this ?
    }

Upvotes: 5

Related Questions