【问题标题】:Input Char in Doubly Linkedlist C在双向链表 C 中输入字符
【发布时间】:2021-05-25 08:43:45
【问题描述】:

这是我的代码:

struct Node{
    int data;

    char nim[12];

    struct Node *next, *prev;
};
struct Node *head, *tail;

void init(){
   head = NULL;
   tail = NULL;
}

int isEmpty(struct Node *h){
    if(h==NULL)
        return 1;
    else
        return 0;
}

void addData(char *nimI){

struct Node *baru;
baru = malloc(sizeof *baru);

baru->nim = malloc(12 * sizeof(char));
strcpy(baru->nim, nimI);
baru->next = NULL;
    baru->prev = NULL;
    if(isEmpty(head)==1){
        head=baru;
        tail=baru;
    }else{
        tail->next=baru;
        baru->prev=tail;
        tail = baru;
    }

    printList(head);
}

int main()
{
  char nimI[12];
  printf("NIM          : "); 
  scanf("%[^\n]#", &nimI); 
  fflush(stdin);
  addData(nimI);
}

我想在我的双向链表中输入char,但是出错了。

错误:

分配给数组类型的表达式(baru 中的错误->nim = malloc(12 * sizeof(char));)

【问题讨论】:

  • char nim[12]; 已经声明了一个 12 个字符的数组,它将作为分配结构的一部分进行分配。你为什么要再次为它分配内存?如果您真的想将其单独分配给结构,请将其更改为char *nim;
  • 它的工作,但输出是变量的地址而不是值@kaylum

标签: c linked-list char malloc doubly-linked-list


【解决方案1】:

你不需要分配数组的内存,所以写起来毫无价值:

baru->nim = malloc(sizeof(char) * 12);

此语句仅在 char[12] -> *char 时才有可能。感谢@kalyum,但老实说,我刚才自己也想通了。

这是程序的最小版本:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Node {
  int data;
  char *nim; // Changed num[12] -> *num
};

void addData(char *nimI) {
  struct Node *baru = malloc(sizeof *baru);
  baru->nim = malloc(sizeof(char) * 12); // Now this will work

  strcpy(baru->nim, nimI); // Copying nimI into baru->nim pointer

  printf("%s\n", baru->nim); // Displaying the result
}

int main(void) {
  char nimI[12] = "Hello there";

  // Passing nimI[] (equivalent to *nimI when passed)
  addData(nimI);

  return 0;
}

这个输出:

Hello there

【讨论】:

  • 它的工作,但输出是变量的地址而不是值
  • @SylviaHelmi 看看编辑。您需要使用%s 格式说明符。
猜你喜欢
  • 2015-07-09
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
  • 2011-05-04
相关资源
最近更新 更多