我不确定你想用CharArr 实现什么:要么你的节点携带数据,而你摆脱了指向 char 数组的指针,或者你希望它成为指向另一个区域的指针字符串所在的位置,去掉数组部分。
第一个版本,节点包含字符:
#include <stdio.h>
#include <stdlib.h>
struct LLNode
{
char *CharArr[10];
struct LLNode *next;
};
struct LLNode * createNode (char val[])
{
struct LLNode *temp;
temp =(struct LLNode *)malloc(sizeof(struct LLNode));
temp-> CharArr[10] = val;
temp-> next = NULL;
return (temp) ;
};
int main ()
{
struct LLNode *head = NULL;
struct LLNode *curr = NULL;
head = curr = createNode ("JAN") ;
printf ("curr->CharArr[10] = %s\n", curr->CharArr[10]) ;
}
第二个版本,指向Node外的一个区域:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct LLNode
{
char *CharArr;
struct LLNode *next;
};
struct LLNode * createNode (char val[])
{
struct LLNode *temp;
temp =(struct LLNode *)malloc(sizeof(struct LLNode));
temp->CharArr = strdup(val);
temp-> next = NULL;
return (temp) ;
};
int main ()
{
struct LLNode *head = NULL;
struct LLNode *curr = NULL;
//char a[10]="JAN";
head = curr = createNode ("JAN") ;
printf ("curr->CharArr = %s\n", curr->CharArr) ;
}
请注意,在这两种情况下,都不会对节点进行清理。在第二个版本中,还需要free()CharArr。
查看 valgind 输出:
$ valgrind ./so
==19670== Memcheck, a memory error detector
==19670== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==19670== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==19670== Command: ./so
==19670==
curr->CharArr = JAN
==19670==
==19670== HEAP SUMMARY:
==19670== in use at exit: 20 bytes in 2 blocks
==19670== total heap usage: 3 allocs, 1 frees, 1,044 bytes allocated
==19670==
==19670== LEAK SUMMARY:
==19670== definitely lost: 16 bytes in 1 blocks
==19670== indirectly lost: 4 bytes in 1 blocks
==19670== possibly lost: 0 bytes in 0 blocks
==19670== still reachable: 0 bytes in 0 blocks
==19670== suppressed: 0 bytes in 0 blocks
==19670== Rerun with --leak-check=full to see details of leaked memory
==19670==
==19670== For lists of detected and suppressed errors, rerun with: -s
==19670== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)