PNC
PNC

Reputation: 357

Return the value of pointer using doublepointer

Code:

#include<stdio.h>
#include<stdlib.h>
void createAndFillList(int** ptr,int ninput){
    int i;
    ptr=malloc(sizeof(int)*ninput);
    for(i=0;i<ninput;i++){
        printf("enter: ");
        scanf("%d",&*(*ptr+i));
    }
    printf("%p\n",&*ptr);               
}

int main(){
    int** ptr;
    int ninput;

    printf("enter how many spaces will be allocated:");
    scanf("%d",&ninput);

    createAndFillList(ptr,ninput); 
    printf("%p\n", &ptr);       

    getch();
    free(ptr);
    return 0;
}

How to return the value of the address of the first ptr or ptr + 0? I tried everything and it seems to crash every time I input more than 1.

Upvotes: 0

Views: 50

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

First of all you should declare a normal pointer in the main function, and then use the address-of operator & when calling the function. Then inside the function you use the dereference operator * when using the pointer-to-pointer.

So in main:

int *ptr;

...

createAndFillList(&ptr, ninput);

And in createAndFillList:

*ptr = malloc(sizeof(int) * ninput);
...
    scanf("%d", &(*ptr)[i]);  /* Or `(*ptr) + i` */

Upvotes: 3

Related Questions