'getting the current number of elements in a matrix to decide when to realloc it
I have a matrix that gets calloced after program start. I then need to figure out when I need to realloc it (after the array is full). My initial thought was to hold a counter variable inside the struct and increment it after each insert, but i'm thinking there is a better way with using the sizeof()? I am using calloc so i do not need to use malloc and memset in conjuction, this means that the indexes that get calloced will be set to 0? So i would need to check how many "non zero" elements there are in the array to know when i have to realloc. I have wrote a simple test program but i am confused by the bottom printf statement that outputs '1'. After the elements are put into this array, they wont be modified in any way, which is why the counter method seems fine to me, but I wanted to test if this worked.
#include <stdio.h>
#include <stdlib.h>
struct c {
char** arr;
};
int main() {
struct c a;
a.arr = calloc(40, sizeof(char*));
for (int x = 0; x < 40; ++x) {
a.arr[x] = calloc(20, sizeof(char));
a.arr[x] = "lol\0";
}
a.arr[30] = "dfsd\0";
printf("%s\n", a.arr[30]);
printf("reallocing...\n");
a.arr = realloc(a.arr, 200 * sizeof(char*));
if (a.arr == NULL) {
printf("failed\n");
}
for (int x = 40; x < 200; ++x) {
a.arr[x] = calloc(20, sizeof(char));
a.arr[x] = "lol\0";
}
for (int x = 0; x < 200; ++x) {
printf("%s\n", a.arr[x]);
}
printf("total size: %i\n", sizeof(a.arr) / sizeof(a.arr[0]));
}
This should not output one but rather the size of the matrix, since the sizeof(a.arr[0]) will give you the size of the char type, then divide it into the size of the array in bytes.
Solution 1:[1]
The sizeof(array)/sizeof(array[0]) mechanism only works for fixed size arrays within the scope of their original declaration. It cannot be used for determining the size of dynamically allocated arrays, not for arrays passed as a single pointer to a function , stored etc - ie where the array has decayed to a pointer
You have to store the size somewhere yourself
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pm100 |
