PeterP24
March 17th, 2012, 04:45 PM
Hello,
I am passing a pointer to a function (through call by reference) in order to allocate memory for it with malloc and to put some values into the newly allocated memory cells, i.e. to initialize it.
I came with the following code:
#include <stdio.h>
#include <stdlib.h>
void fct_b(int **b)
{
int i;
*b = malloc(10*sizeof(int));
for(i = 0; i < 10; i++)
{
(*b)[i]=i;
// printf("%d ", (*b)[i]);
}
}
void fct_c(int ***c)
{
int i, j;
**c = malloc(10*sizeof(int*));
for(i = 0; i < 10; i++)
{
(*c)[i] = malloc(10*sizeof(int));
for(j = 0; j < 10; j++)
{
(*c)[i][j]=10*i+j;
//printf("%d", (*c)[i][j]);
}
}
}
int main(void)
{
int *b, **c;
fct_b(&b);
fct_c(&c);
int i, j;
// level b
/*for(i = 0; i < 10; i++)
{
printf("%d ", b[i]);
}*/
// level c
for(i = 0; i < 10; i++)
{
for(j = 0; j < 10; j++)
printf("%d ", c[i][j]);
}
return 0;
}
I manage to figure out how to do it for a pointer to pointer type (function fct_b). However I was surprised to see that the initialisation works only if I use:
(*b)[i]=i
because
*b[i]=i
doesn't work.
This would be one issue. Another one would be that I tried to expand the experience learned at fct_b to a pointer to a pointer to a pointer case - like the one implemented in function fct_c. I can check that inside the fct.c the pointer is allocated and initialised however it is not working.
I have two questions:
(a) in case of fct_b why does the initialisation works with (*b)[i] = i instead of *b[i] = i ?
(b) in case of fct_c - why does not work?
I am passing a pointer to a function (through call by reference) in order to allocate memory for it with malloc and to put some values into the newly allocated memory cells, i.e. to initialize it.
I came with the following code:
#include <stdio.h>
#include <stdlib.h>
void fct_b(int **b)
{
int i;
*b = malloc(10*sizeof(int));
for(i = 0; i < 10; i++)
{
(*b)[i]=i;
// printf("%d ", (*b)[i]);
}
}
void fct_c(int ***c)
{
int i, j;
**c = malloc(10*sizeof(int*));
for(i = 0; i < 10; i++)
{
(*c)[i] = malloc(10*sizeof(int));
for(j = 0; j < 10; j++)
{
(*c)[i][j]=10*i+j;
//printf("%d", (*c)[i][j]);
}
}
}
int main(void)
{
int *b, **c;
fct_b(&b);
fct_c(&c);
int i, j;
// level b
/*for(i = 0; i < 10; i++)
{
printf("%d ", b[i]);
}*/
// level c
for(i = 0; i < 10; i++)
{
for(j = 0; j < 10; j++)
printf("%d ", c[i][j]);
}
return 0;
}
I manage to figure out how to do it for a pointer to pointer type (function fct_b). However I was surprised to see that the initialisation works only if I use:
(*b)[i]=i
because
*b[i]=i
doesn't work.
This would be one issue. Another one would be that I tried to expand the experience learned at fct_b to a pointer to a pointer to a pointer case - like the one implemented in function fct_c. I can check that inside the fct.c the pointer is allocated and initialised however it is not working.
I have two questions:
(a) in case of fct_b why does the initialisation works with (*b)[i] = i instead of *b[i] = i ?
(b) in case of fct_c - why does not work?