Coding problem using a 2-d array of structs inside another struct in C

前端 未结 5 777
醉酒成梦
醉酒成梦 2021-02-06 10:58

I am working with a 2-dimensional array of structs which is a part of another struct. It\'s not something I\'ve done a lot with so I\'m having a problem. This function ends up f

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 11:33

    I don't think sizeof imageArr works as you expect it to when you're using runtime-sized arrays. Which, btw, are a sort of "niche" C99 feature. You should add some printouts of crucial values, such as that sizeof to see if it does what you think.

    Clearer would be to use explicit allocation of the array:

    thisImage.arr = malloc(thisImage.width * thisImage.height * sizeof *thisImage.arr);
    

    I also think that it's hard (if even possible) to implement a "true" 2D array like this. I would recommend just doing the address computation yourself, i.e. accessing a pixel like this:

    unsigned int x = 3, y = 1; // Assume image is larger.
    print("pixel at (%d,%d) is r=%d g=%d b=%d\n", x, y, thisImage.arr[y * thisImage.width + x]);
    

    I don't see how the required dimension information can be associated with an array at run-time; I don't think that's possible.

提交回复
热议问题