Hi,
I have the following problem: i must allocate a dynamic array from a subroutine which should return such array to main function. The subroutine has already a return parameter so i thought of pass the array as I/O parameter. I tried the following program but it doesn't work (segmentation fault), i think because i should have a pointer to array, but i'm not sure.
void main(){
int *array;
int **ptr = &array;
sub(ptr);
}
void sub(int **ptr){
....//calculates the array dimension
*ptr = calloc(n,sizeof(int));
for(i=0;i<n;i++)*ptr=i;
}
Because you are skipping a step in allocating memory...*ptr has been calloced w/o first allocating memory for ptr which is a dual-level pointer while *ptr is a single-level.
Also: main always returns an int. It is never void. If your compiler does not complain, it is probably an ancient one. There are a lot of reasons here are two
-
You will get random garbage returned to the calling program or shell
-
Some compilers implement the stack frame for void functions differently than for int functions - for optimization reasons - resulting in a almost impossible to debug crash when main() ends.
shamrock could you correct my code please??
void sub(int **ptr) {
ptr=(int**)calloc(n,sizeof(int*));
for(i=0;i<n;i++) {
ptr=(int*)calloc(1,sizeof(int));
*ptr=i;
}
}
ok but in this way i lose the array when sub returns...
If you pass a pointer to the array you won't lose it then.
Hi Shamrock,
*ptr has already been initialized with address of local variable 'array' as -
*ptr = &array; in statement int **ptr = &array;
ptr(int**) -> array(int*) -> (uninitialized/invalid reference to integer).
ptr = &array;
ptr (or array) = (int)calloc(n,sizeof(int)); will initialize array to hold address of allocated memory.
Correction -
*ptr has already been initialized with address of local variable 'array' as -
*ptr = &array; in statement int **ptr = &array;
ptr has already been initialized with address of local variable 'array' as -
ptr = &array; in statement int **ptr = &array;
Sorry Shamrock but I did not understand your answer.Should ptr be a pointer to array??
I tried the following and it seems to work fine:
int main(){
int *array;
int **ptr = &array;
sub(ptr);
}
void sub(int *ptr){
//calculates n...
int *tmp=(int)calloc(n,sizeof(int));
for(i=0;i<n;i++)
tmp[i]=i;
*ptr=tmp;
}
littleboyblu,
Can you try this one -
void main(){
int *array;
int **ptr = &array;
sub(ptr);
}
void sub(int **ptr){
....//calculates the array dimension
*ptr = calloc(n,sizeof(int));
for(i=0;i<n;i++)
(*ptr)[i]=i; // subscript operator [] have higher precedence than dereference * operator
}