Hi all,
I 'm having a bit of trouble understanding about the use of malloc for 1d and 2d arrays., and I would appreciate if someone could tell me what is correct. Lets say for 1d arrays, which is correct?
vector = malloc(length*sizeof(vector));
or
vector = malloc(length*sizeof(*vector));
and for 2d arrays:
Code:
matrix=malloc(rows*sizeof(matrix));
for (i=0; i<columns; i++)
matrix[i]=malloc(columns*sizeof(matrix[i]));
or
Code:
matrix=malloc(rows*sizeof(*matrix));
for (i=0; i<columns; i++)
matrix[i]=malloc(columns*sizeof(*matrix[i]));
I've tried both with gcc and all warnings/pedantic flags on, but both produce the same result (and no warnings) when I put some values in vector and array and then display them.
I've also seen (assuming vector and matrix are unsigned integers
Code:
vector = malloc(length*sizeof(unsigned int*))
and
Code:
matrix=malloc(rows*sizeof(unsigned int *));
for (i=0; i<columns; i++)
matrix[i]=malloc(columns*sizeof(unsigned int));
Ideally I'd like to avoid this in case I want to chenge the type of vector or matrix eg from float to double.
Thank you
Spiros