Reputation: 355
#include <stdlib.h>
#include <stdio.h>
#define MAX_NUM 65536
struct Test{
int t;
char args[16][65];
};
int main(int argc, char ** argv) {
//
struct Test *array = malloc(MAX_NUM * sizeof(struct Test*));
printf("%d", sizeof(*array));
for(int i = 0; i < sizeof(*array); i++) {
printf("%d", i);
printf(" ");
array[i].t = 0;
}
array[421].t = 5;
printf("%d", array[421].t);
free(array);
return 0;
}
Hi, how do I determine how many slots of an array I have after mallocing it? When I print sizeof(*array) I get the number 1044, but when I try to run through the loop and set a test value in each slot I only get to 282 before segfaulting. What is the difference between sizeof and malloc? Why does my array only accept values up to 282 when the size of says it is 1044? Why can I edit a slot at 421 but it segfaults up to 282 in my loop? Thank you
Upvotes: 0
Views: 1463
Reputation: 507
The malloc is wrong: you must use sizeof(struct Test) without *. You should also use MAX_NUM as number of iterations.
sizeof(*array) returns the size of the first element of the array so sizeof(struct Test), not the length of the array.
#include <stdlib.h>
#include <stdio.h>
#define MAX_NUM 65536
struct Test{
int t;
char args[16][65];
};
int main(int argc, char ** argv) {
//Changed Key to Test type
struct Test *array = (Struct Test*)malloc(MAX_NUM * sizeof(struct Test));
printf("%d", sizeof(*array));
for(int i = 0; i < MAX_NUM; i++) {
printf("%d", i);
printf(" ");
array[i].t = 0;
}
array[421].t = 5;
printf("%d", array[421].t);
free(array);
return 0;
}
Upvotes: 1
Reputation: 30146
For a statically-allocated array, you can use sizeof(array)/sizeof(*array)
:
The total amount of memory that array
occupies is sizeof(array)
.
The amount of memory that a single entry occupies is sizeof(*array)
.
Hence, the number of entries in array
is sizeof(array)/sizeof(*array)
.
For a dynamically-allocated array, however, you will have to use the value of MAX_NUM
, since array
is a pointer, hence sizeof(array)
= size of a pointer, which is 4 or 8 bytes (depending on your system).
Upvotes: 1
Reputation: 10667
I think you mean
struct Test *array = malloc(MAX_NUM * sizeof(struct Test));
Or am I missing something ?
Upvotes: 1