gpt4 book ai didi

c - 结构数组奇怪的输出?

转载 作者:行者123 更新时间:2023-11-30 19:49:01 25 4
gpt4 key购买 nike

任何人都可以告诉我为什么结构数组不能正确打印吗?

我认为这与我分配给我不确定的结构的内存有关!

使用 mac osx mountain lion xcode 4 gcc

感谢您的帮助,完全陷入困境!(请耐心等待,我只是一名学生!)

#include <stdio.h>
#include <limits.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>



typedef struct{
char* one;
char* two;
} Node;

Node *nodes;
int count = 0;


//-----------------------------------------------------------------------
void add(char *one,char*two){

char x[40];
char y[40];

printf("reached..\n");

strcpy(x,one);
strcpy(y,two);


printf("--> X: %s\n",x);
printf("--> Y: %s\n",y);

Node newNode;
newNode.one = x;
newNode.two = y;
nodes[count]= newNode;

count++;
}
//-----------------------------------------------------------------------

//-----------------------------------------------------------------------
void print(){

int x;
for (x = 0; x < 10; x++)
{
printf("%d : (%s, %s) \n",x,nodes[x].one, nodes[x].two);
}

}

//-----------------------------------------------------------------------

//-----------------------------------------------------------------------
void check(char **arg)
{

if(strcmp(*arg, "Add") == 0)
{

add(arg[1],arg[2]);

}else if(strcmp(*arg,"print") == 0)
{

print();
}else{
printf("Error syntax Enter either: \n Add [item1][item2]\n OR \n print\n");
}

}
//-----------------------------------------------------------------------
void readandParseInput(char *line,char **arg)
{

if (fgets (line, 512, stdin)!= NULL) {


char * pch;
pch = strtok (line," \n\t");
int count = 0;
arg[0] = pch;

while (pch != NULL)
{
count++;
pch = strtok (NULL, " \n\t");
arg[count] =pch;
}


}else{
printf("\n");
exit(0);
}

}

//-----------------------------------------------------------------------

int main()
{


int size = 100;
nodes = calloc(size, sizeof(Node));

int i;
for(i = 0;i <100; i++){

printf("%s , %s \n",nodes[i].one,nodes[i].two );
// nodes[i].one = ".";
// nodes[i].two = ".";
}


char line[512]; /* the input line */
char *arg[50]; /* the command line argument */

while (1)
{
readandParseInput(line,arg);
if(arg[0] != NULL){
check(arg);
}

}

return(0);
}

最佳答案

您将保留指向以下自动变量的指针:

 char x[40];
char y[40];

add()返回时,这些会超出范围,留下悬空指针。

您必须将 Node::oneNode::two 转换为数组,或者在堆上为它们分配内存。

关于c - 结构数组奇怪的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15957082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com