使用结构传输变量(Transferring variables using structure)

编程入门 行业动态 更新时间:2024-10-25 18:29:16
使用结构传输变量(Transferring variables using structure)

我想使用结构传输几个变量。 以下是示例程序代码。 当我运行这个程序时,我得到分段错误。 我用gcc编译器。

谁能帮我这个?

struct data{ const char * ip; const char * address; const char * name; }; int fun(struct data *arg) { //struct data *all; const char *name = arg->name; printf("\n My name is:%s",name); return 1; } int main(int argc, char * const argv[]) { struct data * all; int k=0; //data.name = argv[1]; all->name=argv[1]; k = fun(all); printf("\n k is:%d ",k); return 0; }

I want to transfer few variables using structure. Following is the sample program code. When I run this program, I get segmentation fault. I use gcc compiler.

Can anyone help me with this?

struct data{ const char * ip; const char * address; const char * name; }; int fun(struct data *arg) { //struct data *all; const char *name = arg->name; printf("\n My name is:%s",name); return 1; } int main(int argc, char * const argv[]) { struct data * all; int k=0; //data.name = argv[1]; all->name=argv[1]; k = fun(all); printf("\n k is:%d ",k); return 0; }

最满意答案

问题出在这里:

struct data * all; all->name=argv[1];

你还没有为all分配内存。 当你有一个未初始化的指针时,它指向内存中的随机位置,你可能无法访问它们。 你有两个选择:

在堆栈上分配:

struct data all; all.name=argv[1]; k = fun(&all);

在堆上分配:

struct data *all = malloc(sizeof(*all)); if (all != NULL) { all->name=argv[1]; k = fun(all); } free(all);

当你知道只有当前函数(以及你调用的那些函数)才需要all函数时,第一种情况就是好的。 因此,在堆栈上分配它就足够了。

第二种情况适用于需要创建它的all函数之外的all函数,例如当您返回它时。 想象一下,一个函数初始化all并返回给其他人使用。 在这种情况下,您无法在堆栈上分配它,因为它会在函数返回后被销毁。

您可以在此问题中阅读更多相关信息。

The problem is here:

struct data * all; all->name=argv[1];

You have not allocated memory for all. When you have an uninitialized pointer, it is pointing to random locations in the memory, which you probably won't have access to. You have two options:

Allocate on the stack:

struct data all; all.name=argv[1]; k = fun(&all);

Allocate on the heap:

struct data *all = malloc(sizeof(*all)); if (all != NULL) { all->name=argv[1]; k = fun(all); } free(all);

The first case is good when you know that all will be needed only in the current function (and those you call). Therefore, allocating it on the stack is sufficient.

The second case is good for when you need all outside the function creating it, for example when you are returning it. Imagine a function initializing all and return it for others to use. In such a case, you can't allocate it on the stack, since it will get destroyed after the function returns.

You can read more about it in this question.

更多推荐

本文发布于:2023-08-02 18:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1380012.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   结构   Transferring   variables   structure

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!