c - 结构上的指针不能复制到函数内的另一个指针

标签 c list pointers struct copy

<分区>

我有一个问题,这听起来很愚蠢,但我就是不明白。我尝试使用以下结构为列表编写一个小 shell:

struct shellvalue {
    char* word;
    char isorder;
    char isarg;
    char ispipe;
    char isamp;
    unsigned int wordcount;
    unsigned int ordercount;
    struct shellvalue* next;
};

我在主方法中启动了两个指针

struct shellvalue* start;
struct shellvalue* current;

然后我现在为第一个元素分配内存:

void addtoken(char* word, int counter, struct shellvalue* start,
    struct shellvalue* current)
{
  if (counter == 0)
  { //creating first element
    size_t structsize = sizeof(struct shellvalue);
    struct shellvalue* tmp = (struct shellvalue*) malloc(structsize);
    tmp->word = malloc(strlen(word) + 1);
    strcpy(tmp->word, word);
    start = tmp;
    start->next = NULL;
    current = start;
  }
  else
  { // append new element
    struct shellvalue* new = (struct shellvalue*) malloc(
        sizeof(struct shellvalue));
    new->word = malloc(strlen(word) + 1);
    strcpy(new->word, word);
    current->next = new;
    current = new;
  }
}

但是当我尝试做的时候

start = tmp;

我可以在调试器中看到,start 的值仍然是来自 main-Method 的 NULL。这两个指针对我来说似乎是同一类型,我没有收到警告或任何带有此编译器标签的内容

-Wall -ansi -Wconversion -pedantic -m64

我真的不明白,我做错了什么。

最佳答案

您的赋值 start = tmp 仅更改 addtoken()start 的值。由于指针是按值传递的,因此这不会更改函数外的指针 start。为了实现这一点,您必须将一个指向指针的指针传递给您的函数:

void addtoken(char* word, int counter, struct shellvalue** start, struct shellvalue** current) {
    // ..
    // replace assignments to start/current with:
    *start = tmp
    // ..
}

然后,在调用您的函数时:

struct shellvalue* start;
struct shellvalue* current;

addToken(word, counter, &start, &current);

我建议的替代方案:

使用一个结构来保存你的两个指针,并将指向它的指针传递给你的函数:

struct shellvalue_list {
    struct shellvalue* start;
    struct shellvalue* end;
};

void addtoken(struct shellvalue_list* list, char* word, int counter) {
    // ..
    list->start = tmp;
    // ..
}

这是 C 中面向对象代码的常见用法。

关于c - 结构上的指针不能复制到函数内的另一个指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23427636/

相关文章:

c - void function(stuct *s) 与 void function(stuct s) 有什么区别?

c - 如何使用 expat 找到流中 XML 文档的结尾?

python - 如何将列表拆分为更小的列表?

c# - 更新列表而不修改父级

java - java中比较多个整数并找到最大的

Java:引用 JSON 中的键值

c - GCC错误结构灵活数组成员没有命名成员

c++ - CUDA:错误:创建 thrust::device_ptr 时出现 "transfer of control bypasses initialization of"

c - 如何获得这个C程序的输出?

c - 二维数组结构出现段错误