I have this C function:
fill_array(&data, &size);
void fill_array(int **data, int *size){
printf("Size is:");
scanf("%d", size);
*data = malloc(*size * sizeof(int *));
int i = 0;
for (i = 0; i < size; i++){
(*data)[i] = rand() % 11;
}
}
I want to assign data[i] for example, to random number. How to do such a thing? I have tried many variations, but all of the time my program crashes. Thanks.
type *var = malloc(size * sizeof(*var));instead oftype *var = (type *)malloc(size * sizeof(type));. The first one is much cleaner, and much more maintainable. If you change the type ofvar, you don't run the risk of allocating wrong size of memory because you forgot to changetypeeverywhere. In short, don't repeat yourself.sizeof(int *)in yourmallocwhich should have beensizeof(int). If you had listened to my previous comment, this error wouldn't have happened.