TransWikia.com

Pointer value in c

Stack Overflow Asked by gsoap on February 15, 2021

Generally speaking, a pointer’s value inside a function in c is local or can be accessed in main through the pointer?

Example code:

size_t *function(int a, int *b)
{   
    int d;
    size_t *array;
    b = &d;
    //DO STUFF HERE
    printf("%d", *b); //This gets printed right
    return array;

  }
int main()
{
    size_t *array2;
    int *b;

    array2 = function(a, b);
    printf("%d", *b);   //This gives seg fault

}

3 Answers

As Arkku says Arguments are local variables, you can treat the pointer as an address value like 0x7fff13f1ce3c, then it's pretty easy to understand.

typedef address int*
typedef address2 size_t*

size_t *function(int a, address b)
{   
    int d;
    address2 array;
    b = &d;
    //DO STUFF HERE
    printf("%d", *b); //This gets printed right
    return array;

  }
int main()
{
    address2 array2;
    address b;

    array2 = function(a, b);
    printf("%d", *b);   //This gives seg fault

}

Change the value of b in function won't influence the value of b in main. As for the array, function will return An address value.

Answered by 肖海飚 on February 15, 2021

In function main you pass the pointer b to function but b is uninitialized (can contain any value):

array2 = function(a, b);

Thefore this makes no sense. Inside function, If you want to modify b you need to instead call function like this:

int b;

array2 = function(a, &b);

The function can now assign to *b.

Answered by August Karlstrom on February 15, 2021

Arguments are local variables, so you are not actually assigning to main's pointer, you are just ignoring the value passed as argument and assigning to the local b in function. You need a pointer to pointer int **b argument in order to assign to the b in main.

Also, the assigned address is that of a local variable d, which ceases to exist when function returns so accessing it afterwards through a pointer would be invalid regardless (undefined behaviour, even if it might happen to work before it gets overwritten on the stack).

edit: If your goal is to get the value of d to main, you don't need a pointer in main, so instead of b you can have int d in main and pass its address &d to function (function(a, &d)), then you can assign to main's d in function with *b = d.

Answered by Arkku on February 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP