双链接列表C中的输入字符
这是我的代码:双链接列表C中的输入字符,c,linked-list,char,malloc,doubly-linked-list,C,Linked List,Char,Malloc,Doubly Linked List,这是我的代码: 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
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
时,此语句才可能出现。多亏了,但老实说,我刚才自己就知道了
以下是该程序的最低版本:
#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;
}
您不需要分配数组的内存,因此写入以下内容毫无意义:
baru->nim = malloc(sizeof(char) * 12);
只有当char[12]
->*char
时,此语句才可能出现。多亏了,但老实说,我刚才自己就知道了
以下是该程序的最低版本:
#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;
}
charnim[12]已经声明了12个字符的数组并将作为分配结构的一部分进行分配的代码>。你为什么要再次为它分配内存?如果您真的想将其单独分配给struct,那么将其更改为char*nim代码>。这是可行的,但输出是变量的地址,而不是@kaylumchar nim[12]的值已经声明了12个字符的数组并将作为分配结构的一部分进行分配的代码>。你为什么要再次为它分配内存?如果您真的想将其单独分配给struct,那么将其更改为char*nim代码>。这是工作,但输出是变量的地址,而不是@kaylumit的工作值,但输出是变量的地址,而不是value@SylviaHelmi看编辑。您需要使用%s
格式说明符。它可以工作,但输出是变量的地址,而不是value@SylviaHelmi看编辑。您需要使用%s
格式说明符。