简体   繁体   中英

Segmentation fault when working with a 2d array of structures in c

I created a 2d array of structures and now I want to assign values to x, y, and z. Any ideas where the segmentation fault is coming from?

struct xyz
{
    int x;
    int y;
    int z;
};

char buf[80];

struct xyz array[width][height];

for(row=1;row<=width;row++)
{
    for(col=1;col<=height;col++)
    { 
        fgets(buf,80,file);
        array[row][col].x = strtol(buf, NULL, 10);
        fgets(buf,80,file);
        array[row][col].y = strtol(buf, NULL, 10);
        fgets(buf,80,file);
        array[row][col].z = strtol(buf, NULL, 10);
    }
}

Arrays start from 0 in C. You're stepping outside the allocated space since you're accessing array[width] . Perhaps you want:

for(row = 0; row < width; row++)
          ^      ^

Remember, if you declare type array[LENGTH] , it's never valid to touch the element array[LENGTH] . The last valid element is LENGTH - 1 .

Your loops are going one out of bounds on the final iteration.

Your array size is width wide and height deep, so the first index is [0][0] and the maximum valid index is [width - 1][height - 1] . However, you use <= in your conditions, so you actually index [width][height] on the last iteration.

Also, arrays start from index 0 , not 1 , so start your loops from 0 instead of 1 and use < , not <= .

SI there a reason you're running from 1 to hight/col? In C all array begin in 0 and end in length-1.

In other word the for loops should look like:

for(row=0;row<width;row++)
{
   for(col=0;col<height;col++)
   { 

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