C:char数组数据被覆盖
我正在尝试编写代码来输出列表(学习 linkedList 的作业)。我有用于在末尾添加元素到 linkedList 并管理指针的代码:
void addEnd( LinkedList *someList, void *newData )
{
Node *newNode = malloc ( sizeof ( Node ) );
newNode->data = newData; // set the fields of the new Node
newNode->next = someList->header;
newNode->prev = someList->header->prev;
someList->header->prev->next = newNode; // splice-in the newNode
someList->header->prev = newNode; // into the List
someList->size++;
}
我遇到的一些问题是 stdin 并使其正确输出。
char currChar = getchar();
while(currChar != EOF)
{
if (currChar == 'a')
{
currChar = getchar();//Skip over space
if (currChar == SPACE)
{
//Get the name to add to list (must be less than 20 characters)
currChar = getchar();
char name[MAX_NAME_LENGTH] = {0};
int count = 0;
while (count<MAX_NAME_LENGTH && currChar != NEWLINE)
{
name[count] = currChar;
currChar = getchar();
count++;
}
currChar = getchar();
addEnd(roster, name);
outputList(roster);
}
else // If no space after 'a' then exit
exit(1);
}
else
exit(1);
}
输出:
[alice]
[bob bob]
[chad chad chad]
[dan dan dan dan]
我相当确定问题出在: “字符名称[MAX_NAME_LENGTH] = {0};”
因为,如果我理解正确的话,这对每个名称使用相同的字符数组。只是不确定如何避免这种情况。有没有办法使用指针来实现我在这里想要的?
I am trying to write code to output a list (homework assignment for learning linkedLists). I have code for adding an element to a linkedList, at the end, and managing the pointers:
void addEnd( LinkedList *someList, void *newData )
{
Node *newNode = malloc ( sizeof ( Node ) );
newNode->data = newData; // set the fields of the new Node
newNode->next = someList->header;
newNode->prev = someList->header->prev;
someList->header->prev->next = newNode; // splice-in the newNode
someList->header->prev = newNode; // into the List
someList->size++;
}
Where i'm running into some issues is with stdin and getting it to output properly.
char currChar = getchar();
while(currChar != EOF)
{
if (currChar == 'a')
{
currChar = getchar();//Skip over space
if (currChar == SPACE)
{
//Get the name to add to list (must be less than 20 characters)
currChar = getchar();
char name[MAX_NAME_LENGTH] = {0};
int count = 0;
while (count<MAX_NAME_LENGTH && currChar != NEWLINE)
{
name[count] = currChar;
currChar = getchar();
count++;
}
currChar = getchar();
addEnd(roster, name);
outputList(roster);
}
else // If no space after 'a' then exit
exit(1);
}
else
exit(1);
}
Output:
[alice]
[bob bob]
[chad chad chad]
[dan dan dan dan]
Im fairly certain the issue is with:
"char name[MAX_NAME_LENGTH] = {0};"
Since, if i'm understanding correctly, this is using the same char array for each name. Just unsure of how to avoid this. Is there a way to use pointers to achieve what I want here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论