I have a struct with a single member. This member is actually a pointer to pointer to integer, in order to represent a 2-dimensional integer array.
Can I use scalar initialization while creating an instance of that struct?
I am trying to create a 2-dimensional array to represent a collection of pixels for an algorithm exercise.
I should represent something like this:
{
{ 0, 0, 1, 0, 0 },
{ 0, 1, 1, 1, 0 },
{ 1, 1, 1, 1, 1 }
}
In order to represent a generic abstraction of an image, I tried to create a struct with the following structure:
struct image_t
{
unsigned short int** pixels;
};
And so I try to init an instance of that by using:
int
main()
{
struct image_t image = {
{
{0, 0, 1, 0, 0},
{0, 1, 1, 1, 0},
{1, 1, 1, 1, 1},
}
};
return 0;
}
When I try to compile, the following warnings are given:
gcc -I src src/main.c -o bin/flood-fill.bin
src/main.c: In function ‘main’:
src/main.c:41:5: warning: braces around scalar initializer
{
^
src/main.c:41:5: note: (near initialization for ‘image.pixels’)
src/main.c:42:7: warning: braces around scalar initializer
{0, 1, 0},
^
src/main.c:42:7: note: (near initialization for ‘image.pixels’)
src/main.c:42:11: warning: excess elements in scalar initializer
{0, 1, 0},
^
src/main.c:42:11: note: (near initialization for ‘image.pixels’)
src/main.c:42:14: warning: excess elements in scalar initializer
{0, 1, 0},
After making some research, I realized that, as it is gonna be an image representation, each row will have the same total of columns. Due that, I can just use a single array and store everything in a single block of memory. It resolves my problem.
However, as a curious guy, I would like to know if there is any way to use scalar initialization for such cases - if so, how can I do that?
Most likely I'm missing some critical basic concept from C language, so explanations are more than welcome. I really want to understand better the way it works under the hood.