问题描述
这是我的代码:
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));)
解决方法
不需要分配数组的内存,所以写起来毫无价值:
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