指针和数据结构

时间:2014-02-12 14:37:09

标签: c pointers data-structures

我的目标是为我的数据结构创建推送功能。

我正在尝试做什么:

  1. 要求客户输入三个字符的对象,例如。框
  2. 然后将obj名称传递给push函数(现在head和tail指针为null)
  3. 然后计算机将为此分配内存,然后该函数将返回一个内存地址
  4. 然后我将使用该地址将obj名称存储到我的对象Array。
  5. 我正在尝试逐步完成这个数据结构,至于现在我似乎无法将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;
        }
    
    }
    
    }
    

1 个答案:

答案 0 :(得分:0)

在这一行:

 head = push(objname, *head, *tail);

您正在解除引用headtail并且尚未为其分配任何内存。这是未定义的行为。

分配指针或传入指针:

 head = push(objname, head, tail);

您的程序中还有其他错误。就像您push的第一个参数是char一样,但是你传递了char[]

相关问题