我的目标是为我的数据结构创建一个推送函数。
我正在尝试做的事情:
- 要求客户输入三个字符的 obj 单词,例如。盒子
- 然后 obj 名称将被传递给 Push 函数(目前头指针和尾指针为空)
- 计算机将为此分配内存,然后该函数将返回一个内存地址
- 然后我将使用该地址将 obj 名称存储到我的对象数组中。
我正在尝试一步一步地完成这个数据结构,目前我似乎无法将 obj 名称保存到 objArray 中。我可以不返回指针吗?
#include <stdio.h>
#include <string.h>
char *push(char element, char *head, char *tail){
char *dq;
dq = (char*)malloc(4*sizeof(char));
head=dq;
return head;
}
int main(){
char input[7];
char command[7];
char objArr;
char objname[4];
char *head;
char *tail;
while(printf("Choose from the ff operations by typing:\npush\npop\ninject\neject\nexit\nInput Command: ")&&fgets(input, 6, stdin)){
sscanf(input, "%s", command);
if(strcmp(command, "exit")==0){
break;
}
if(strcmp(command, "push")==0){
printf("Input an object name to push: ");
fgets(objname, 4, stdin);
head = push(objname, *head, *tail);
objArr[head] = objname;
printf("%s", objArr[head]);
break;
}
if(strcmp(command, "pop")==0){
break;
}
if(strcmp(command, "inject")==0){
break;
}
if(strcmp(command, "eject")==0){
break;
}
}
}
最佳答案
在这一行中:
head = push(objname, *head, *tail);
您正在取消引用 head
和 tail
并且尚未为其分配任何内存。这是未定义的行为。
分配指针或像这样传递它:
head = push(objname, head, tail);
您的程序中还存在其他错误。就像您的 push
的第一个参数是 char
一样,但您向它传递了一个 char[]
关于c - 指针和数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21730959/