-3
名前を格納する構造体にcharポインタがあります。値を挿入して名前の最後の値を印刷すると、すべてのノードで印刷されます。 、あなただけではなく、単一のポインタを割り当て、あなたの文字列をコピーされることはありませんあなたのコードで構造体に文字列のポインタを持つ
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
typedef struct test_s {
int id;
char *p;
struct test_s *next;
} test_t;
test_t** add(test_t **root, int id, char const *name){
size_t len = strlen(name);
test_t *newnode=(test_t*)malloc(sizeof(test_t)+len+1); // 1 goes for \0 terminator
newnode->id=id;
strcpy(newnode->p=(void*)(newnode+1), name);
newnode->next=NULL;
test_t **tail = root;
while (*tail) {
tail = &(*tail)->next;
}
*tail = newnode;
return &(newnode->next);
}
問題:
typedef struct tests{
int id;
char *p;
struct tests *next;
}test;'
'void add(test **root,int id,char *name){
test *newnode=(test*)malloc(sizeof(test));
newnode->id=id;
newnode->p=name;
newnode->next=NULL;
test *curr;
curr=(*root);
if((*root)==NULL){
(*root)=newnode;
}
else{
while(curr->next!=NULL){
curr=curr->next;
}
curr->next=newnode;
}
}
newnode-> p = name; 'newnode-> p = strdup(name);のように変更してください。 – BLUEPIXY
名前のハードコピーを使用する予定ですか? 'p'にメモリを割り当てないからです。 'name'は何を指していますか?文字列リテラルですか?なぜそれはconstではないのですか? – Lundin
なぜ初心者は結果を単に返すのではなく、ほとんどいつも2つ星のポインタを使用しますか? – Olaf