我写了一段代码,用于打印单链表数组中的单词。但当我运行代码时,它会打印(null)
,但不会打印JAN
。我不知道为什么它一直在打印null
。有人能帮我吗?
这是我的代码:
#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;
//char a[10]="JAN";
head = curr = createNode ("JAN") ;
printf ("curr->CharArr[10] = %sn", curr->CharArr[10]) ;
}
超出范围的索引。您的程序是未定义的,但它简化为非常简单的程序。
temp-> CharArr[10] = val;
temp-> next = NULL;
CharArr
只有十个元素,并且您向不存在的第十个元素写入,所以当您向temp->next
写入时,您覆盖了val
。
也许你认为数组的索引从1到n,但它们的索引从0到n。
要查看此工作,请将char *CharArr[10];
更改为char *CharArr[11];
。但你可能想重新考虑一下这种类型。看起来您的意思是char CharArr[10];
,并通过调用strcpy
(#include <string.h>
(来填充它。
我不确定你想用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] = %sn", curr->CharArr[10]) ;
}
第二个版本,指向节点外的区域:
#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 = %sn", curr->CharArr) ;
}
请注意,在这两种情况下,都不会对节点进行清理。在第二个版本中,您还需要free()
和CharArr
。
参见价值输出:
$ 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)