我有一个问题,这听起来真的很愚蠢,但我只是没有得到它。我尝试使用以下Struct编写一个小shell来获取列表:
struct shellvalue {
char* word;
char isorder;
char isarg;
char ispipe;
char isamp;
unsigned int wordcount;
unsigned int ordercount;
struct shellvalue* next;
};
我使用
在main方法中启动了两个指针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仍然是main-Method的值NULL。两个指针对我来说都是相同的类型,我没有使用这个compilertags
得到任何警告或任何东西 -Wall -ansi -Wconversion -pedantic -m64
我真的不知道,我做错了什么。
答案 0 :(得分:1)
您的作业start = tmp
仅更改start
内addtoken()
的值。由于指针是按值传递的,因此不会改变函数外部的指针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, ¤t);
我建议的替代方案:
使用结构来保存两个指针,并将指针传递给您的函数:
struct shellvalue_list {
struct shellvalue* start;
struct shellvalue* end;
};
void addtoken(struct shellvalue_list* list, char* word, int counter) {
// ..
list->start = tmp;
// ..
}
这是C语言中面向对象代码的常用习惯用法。