So I'm working in C and I have an int **
inside of one function that is modified within another function. I was getting a SegFault when I was running this problem so I decided to debug it with gdb
. What I found was that memory was never allocated to this array. My functions are like this
void declarer()
{
int ** a;
alocator(a, 4, 5);
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
printf("%d\n", a[i][j]);
}
void alocator(int ** a, int b, int c)
{
a = (int **)malloc(sizeof(int *) * b);
for (int i = 0; i < b; i++) {
a[i] = (int *)malloc(sizeof(int) * c);
for (int j = 0; j < c; j++)
a[i][j] = j;
}
}
When I run gdb
with a breakpoint after the line alocator(a, 4, 5)
(before the program segfaults), and I write pa
, I get $1 = (int **) 0x0
which shows that a
is at address 0x0
and has no memory allocated for it. Why did alocator
not allocate memory to it, and how can I get alocator
to allocate memory to a
?
Because you are passing **a
by value, you have to pass it as pointer. So use a triple pointer:
void declarer()
{
int **a;
alocator(&a, 4, 5);
...
}
void alocator(int ***a, int b, int c)
{
*a = (int **)malloc(sizeof(int *) * b);
...
You pass the variable a
by value to the function, so its value won't be changed. You have two solutions:
Either change your function to accept value of type int ***
and pass a
by address, or change the return value of the function to int **
and make use of that value upon invocation.
example:
void declarer()
{
int ** a = alocator(4, 5);
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
printf("%d\n", a[i][j]);
}
int **alocator(int b, int c)
{
int **a = (int **)malloc(sizeof(int *) * b);
for (int i = 0; i < b; i++) {
a[i] = (int *)malloc(sizeof(int) * c);
for (int j = 0; j < c; j++)
a[i][j] = j;
}
return a;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.