简体   繁体   中英

2D array adding extra character

This is my code for appending to the 2D array and displaying it line by line into a grid.

void map_print() {

    char map[head->xdim][head->ydim]; // Generate 2D array for map
    memset( map, 0, sizeof(map));

    FEATURE *temp=head->next; // Get the pointer of the head of linked list

    while(temp!=NULL) // Generated the map with the features
    {
        for (int xdim = 0; xdim < temp->xdim; xdim++){
            map[temp->yloc][temp->xloc + xdim] = temp->type;
            printf("X axis: Appeding to map[%d][%d]\n",temp->yloc,temp->xloc+xdim);
        }
        for (int ydim = 0; ydim < temp->ydim; ydim++){
            map[temp->yloc + ydim][temp->xloc] = temp->type;
            printf("Y axis: Appeding to map[%d][%d]\n",temp->yloc + ydim,temp->xloc);

        }
        temp=temp->next;
    }

    for (int i = 0; i < head->ydim; i++) { // Print out the map
        for (int j = 0; j < head->xdim; j++) {
            //printf("%c ", map[i][j]);
            printf("map[%d][%d](%c)",i,j,map[i][j]);
        }
        printf("\n");
    }
}

在此处输入图片说明

Based on the printf, it should only append to the following coordinates. However, map(1)(4),map(2)(4),map(3)(4),map(4)(4) are printing * which i had not appended to it.

I cant find any line of my code that is adding that extra character

You mixed x and y. The declaration is char map[head->xdim][head->ydim]; ( [x][y] ), but you are using it like map[temp->yloc][temp->xloc + xdim] = temp->type; ( [y][x] ).

If your array's size is [10][5] and you are accessing [0][9] it would invoke undefined behaviour (because of out of bounds access) and one possibility is that it would access [1][4] (the tenth element in the 2D array) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM