1

I'm new to C. I'm having difficulty in understanding the difference between the following two

int N = 16
double (*XX)[2] = malloc(2*N*sizeof(double)); 

and

int N = 16
double *XX[2] = malloc(2*N*sizeof(double)); 

If I write the first one it is getting compiled. However, the second one is giving following error. Please explain

error: invalid initializer

Edit: I also wanted to ask what the malloc is doing in above correct case?

5 Answers5

2

double (*XX)[2] is a pointer to an array with two double elements.

double *XX[2] is a pointer to an array with two double * elements.

malloc is for dynamic memory allocation, for example:

char array_stack[2]; // 2 chars allocated on the stack (no need for free())
char *array_heap = malloc(2 * sizeof(char)); // 2 chars allocated on the heap
// later...
free(array_heap); // heap memory must be freed by user

FYI:

char array_stack[2]; // this is nevertheless a pointer
char *array = array_stack; // this works, because array_stack is a pointer to a char

For more information about the stack and heap: Stack vs Heap

double *XX[2] = malloc(2*N*sizeof(double)); 

Does not work because it expects two elements as initializer. For example:

double _1, _2;
double *XX[2] = {&_1, &_2};

If you want do to this with malloc you need to change it to a pointer to an array with double pointers like this:

double **XX = malloc(...);
Marco
  • 7,007
  • 2
  • 19
  • 49
1

In this case

 double (*XX)[2]

XX is a pointer to array of 2 doubles

In this case

 double *XX[2]

XX is array of 2 pointers to double

EDIT: Others have explained malloc, but in laymans terms: With malloc you reserve a amount of memory on your computer using malloc, and then store values in the memory you have reserved with malloc

smushi
  • 701
  • 6
  • 17
0
  1. malloc would return a pointer to some memory location (void*).
  2. double (*XX)[2] is a pointer to an array of doubles - no problem: compiler knows how to cast from void* to double*.
  3. double *XX[2] is an array of double pointers (I prefer write it this way double* XX[2] it is easier, for me, understand that we are talking about double pointer(s)) - compiler does not know conversion from void* to array of double pointers.
Filippo Lauria
  • 1,965
  • 14
  • 20
0

XX in the first case is just a pointer which point to an array with two double elements. So "sizeof(XX)" is just 4.

Second case: XX is a array name with two element whose type is (double*). So the following code will be OK. double *XX[2]; XX[1]= malloc(20*sizeof(double));

carpenter
  • 33
  • 4
0

The 1st definition double (*XX)[2] defines a single value, a pointer here. A single variable can be initialised by a single value, as returned by = malloc(...).

The 2nd (double *XX[2]) defines an array. Array initialisers look like this = {<init value(s)>}.

alk
  • 69,737
  • 10
  • 105
  • 255