Is there a way to assign values in an array of arrays?
Specifically, I have written the following code:
#include <stdio.h>
#include <stdlib.h>
void func(int **A){ //A: address of (address that the pointer stores)
int i;
*A=(int *)malloc(5*sizeof(int)); //*A: address that the pointer stores
for (i=0;i<5;i ){
**A=i; //**A: content
}
}
int main(){
int *k, i;
func(&k);
for (i=0;i<5;i ){
printf("%d ", k[i]);
}
return 0;
}
The statement **A=i
inside the function, seems to assign the values only in the first place of the array (the output is 4 0 0 0 0
each time I execute the code).
I have also tried using *A[i]=i
instead. In this case, the compiler terminates the execution with the following message: signal: illegal instruction (core dumped)
.
Is there anything I could do to solve this?
CodePudding user response:
There are several equivalent constructions that allow to do that.
Here you are
for (i=0;i<5;i ){
A[0][i] = i;
}
or
for (i=0;i<5;i ){
( *A )[i] = i;
}
or
for (i=0;i<5;i ){
*( *A i ) = i;
}
CodePudding user response:
The array index operator []
has higher precedence than the dereference operator *
.
You'll need to use parenthesis do what you want.
(*A)[i]=i;