开发者

dereference a pointer

开发者 https://www.devze.com 2023-03-03 22:58 出处:网络
How can I dereference the pointer as i pack the structure in fill function and pass the pointer to send how to dereference it? as i get segmentation fault in what i have done

How can I dereference the pointer as i pack the structure in fill function and pass the pointer to send how to dereference it? as i get segmentation fault in what i have done

#include<s开发者_如何转开发tdio.h>
struct xxx
{
    int x;
    int y;
};

void fill(struct xxx *create)
{
    create->x = 10;
    create->y = 20;
    send(*create);
}


main()
{
    struct xxx create;
    fill(&create);
}

send(struct xxx *ptr)
{
    printf("%d\n",ptr->x);
    printf("%d\n", ptr->y);
}


send(*create) will send the actual struct object, not a pointer.

send(create) will send the pointer, which is what you need.

When your function declaration's arguments contain an asterisk (*), a pointer to something is needed. When you then pass that argument on to another function requiring another pointer, you need to pass the name of the argument, since it is already a pointer.

When you used the asterisk, you dereferenced the pointer. That actually sent the "cell of memory that create points to," the actual struct and not a pointer.


The line

send(*create);

should be

send(create);

The create variable is already a pointer, there is no need for the *


You would not have asked that question if you had asked the compiler to help you (No offense!). The compiler is your friend. Enable it's warnings. For example GCC with

gcc -Wall yourcode.c

gives you

yourcode.c: In function ‘fill’:
yourcode.c: 11:5: warning: implicit declaration of function ‘send’
yourcode.c: At top level:
yourcode.c:15:5: warning: return type defaults to ‘int’
yourcode.c:22:5: warning: return type defaults to ‘int’
yourcode.c: In function ‘send’:
yourcode.c:26:5: warning: control reaches end of non-void function
yourcode.c: In function ‘main’:
yourcode.c:19:5: warning: control reaches end of non-void function

Now you know that you should have written a prototype for function send or moved it's definition above the first usage. And as the compiler assumes a default return type for send you obviously forgot to specify it (here apparently void as you don't have any return value). For main the return type int and an

return 0;

is missing.

With the said modifications the compiler will tell you

yourcode.c: In function ‘fill’:
yourcode.c:12:5: error: incompatible type for argument 1 of ‘send’
yourcode.c.c:7:6: note: expected ‘struct xxx *’ but argument is of type ‘struct xxx’

and you will notice you have one redundant * in

send(*create);

which dereferences your pointer. Note: You do NOT want to dereference your pointer, because you have to forward the pointer to send and not the value. Change the line to

send(create);

et Voilà.

0

精彩评论

暂无评论...
验证码 换一张
取 消