Reputation: 5
#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
struct Array {
uint32_t* row;
};
int main()
{
struct Array* a = malloc(sizeof(struct Array) * 2);
a[0].row = malloc(sizeof(uint32_t) * 3);
a[1].row = malloc(sizeof(uint32_t) * 2);
uint32_t temp1[] = {2,3,4};
uint32_t temp2[] = {5,8};
for(int i=0;i<3;i++)
a[0].row[i] = temp1[i];
for(int i=0;i<2;i++)
a[1].row[i]= temp2[i];
for(int i=0;i<2;i++)
{
int len = sizeof(a[i].row)/sizeof(a[i].row[0]);
for(int j=0;j<len;j++)
{
printf("%d\t",a[i].row[j]);
}
printf("\n");
}
}
I have a multidimensional array. rows in the array can be of different size so i used a structure.
Now I want to print the elements in the array. But its not printing in the right way.
2 3
5 8
This is showing as my output.
int len = sizeof(a[i].row)/sizeof(a[i].row[0]);
I think there is something wrong in the above line. please help me to print the elements of array correctly
Upvotes: 0
Views: 92
Reputation: 67476
It will not work this way as it will give you the size of the pointer in uint32_t
units.
If you want to dynamically allocate the 2D array you need to keep the sizes somewhere in your data. Here is an example (access using array pointer):
typedef struct
{
size_t cols, rows;
uint32_t data[];
}Array2D;
Array2D *alloc2DArray(const size_t rows, const size_t cols)
{
return malloc(rows * cols * sizeof(uint32_t) + sizeof(Array2D));
}
void printArray(const Array2D *arr)
{
uint32_t (*array)[arr -> cols] = (uint32_t (*)[])arr -> data;
for(size_t row = 0; row < arr -> rows; row++)
{
for(size_t col = 0; col < arr -> cols; col++)
printf("%"PRIu32" ", array[row][col]);
printf("\n");
}
}
Sizes are kept in the struct and the actual data in the flexible struct member.
Remember to use the correct type to store the sizes (size_t
)
Upvotes: 1