2D arrays. The first index is incorrect, all the rest are fixed

I have a weird problem and am not sure how to approach it.

I am reading a 50x50 character text file and want to write it to a 50x51 dynamic array (filling in the 51st slot "\ 0").

Then I print the entire array to the console. It should show 50 lines of 50 characters each, since it was an input.

It works well too - except for the first line. For some reason, always wrong.

#define FIELD_SIZE 50
int main(int argc, char** args){
    char* data = ReadFile("start.txt");

    char** map = (char**) malloc( FIELD_SIZE );

    if(map==NULL)
        __debugbreak();

    {
        int i;
        for(i = 0; i < FIELD_SIZE; i+=1){
            map[i] = (char*) malloc(FIELD_SIZE+1);

            if(map[i]==NULL)
                __debugbreak();
            //(FIELD_SIZE+1) in order to skip the '\n' at the end of each line.
            memcpy( &map[i][0], &data[i*(FIELD_SIZE+1)], FIELD_SIZE);
            map[i][FIELD_SIZE] = '\0';
        }
    }


    {
        int i;
        for(i = 0; i < FIELD_SIZE; i+=1){
            printf("%s\n", map[i]); //<-- prints something bad for i==0
        }
    }

    free(data);

    return 0;
}

Here's what my console looks like after running the program: enter image description here The first line is supposed to be "aaaaaaaaaaaaa ...". So it looks like a bad pointer or something like that.

If I reduce FIELD_SIZE to 20 (and read in a text file 20x20 respectively), it works fine.

, . malloc 0, .

VS2010 ++ , C.

+3
2

char ** map = (char **) malloc (FIELD_SIZE);

char ** map = (char **) malloc (FIELD_SIZE * sizeof (char *));

, ​​ . 50 , 50 x 4 /.

+5

. . Memcpy , , , . , , .

memcpy( map[i], &data[i*(FIELD_SIZE+1)], FIELD_SIZE);

, , , .

0

All Articles