Say I have a variable

int * foo;

I pass this variable into

func(int *x)
{
  *x = bar;
}

However, this does not work. However, if I put a non-pointer (say change it to int foo;) and directly put the address in, this works.

Why doesn't my first case work?

Thanks!

有帮助吗?

解决方案 2

By declaring int * foo you've only created a pointer. foo is not actually pointing at anything yet - it's uninitialised. You might even get a segmentation fault from code like that, as the pointer could point outside of program memory. If you do:

int * foo = (int *)malloc(sizeof(int));

You will have initialised the pointer, malloc allocates some memory from the heap of the size passed to it. You can also do:

int bar = 0;
int * foo = &bar;

Which will make foo a pointer to bar (& returns the address of the variable).

其他提示

Your code is doing exactly what you are telling it too. However, int *foo does not allocate any storage. The pointer is simply a handle to a memory address. In this case, it is arbitrary and results in undefined behavior. Try the following instead.

void func(int *x) {
   *x = 42;
}

int main(int argc, char** argv) {
    int *foo;
    int  storage;

    foo = &storage;
    func(foo);
    printf("%d\n" storage);

    return 0;
}

foo is simply a pointer to storage which is allocated on the stack by the runtime. You are just as well off using foo(&storage) in this case.

You should do something like this

int bar = 235; // any value you want

void func(int *x)
{
    *x = bar;
}

int main()
{
    int *foo;
    foo = (int*)malloc(sizeof(int));
    func(foo);

    printf("%d", *foo);
    free(foo);

    return 0;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top