0

我想使用结构传输一些变量。以下是示例程序代码。当我运行这个程序时,我得到了分段错误。我使用 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;
}
4

3 回答 3

3

问题在这里:

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

您尚未为all. 当您有一个未初始化的指针时,它指向内存中的随机位置,您可能无法访问这些位置。你有两个选择:

  1. 在栈上分配:

    struct data all;
    all.name=argv[1];
    k = fun(&all);
    
  2. 在堆上分配:

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

当您知道all仅在当前函数(以及您调用的函数)中需要时,第一种情况很好。因此,将其分配到堆栈上就足够了。

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.

于 2012-07-18T09:56:38.530 回答
3

You need to allocate memory and assign it to the pointer all:

struct data * all;   
int k=0;
all = malloc(struct data);

all->name=argv[1];
k = fun(all);
//...
free(all);

or use a local struct and pass its pointer to the function:

struct data all;   
int k=0;

all.name=argv[1];
k = fun(&all);
于 2012-07-18T09:57:05.440 回答
2

all is a pointer to type struct data. You never assigned it, so it doesn't point to anything.

You need to do one of the following:

  • allocate all on the stack:

    struct data all;

  • allocate all on the heap:


    struct data* all = malloc(sizeof (struct data));   
    // don't forget to check if the allocation succeeded, 
    //and don't forget to free it when you're done
于 2012-07-18T09:56:47.853 回答