gpt4 book ai didi

C:数组元素消失

转载 作者:行者123 更新时间:2023-11-30 20:05:23 25 4
gpt4 key购买 nike

我在弄清楚为什么“myWord”数组中的元素消失时遇到了一些麻烦。 “myWord”和“myLines”都是我的 .h 文件中的全局变量。问题是,如果我将 readWords() 和 printWords() 函数结合起来,那么它就可以工作。那么我做了什么导致“myWord”出现此问题?

这是我的输出:

> Line: 0 (null) 
> Line: 1 (null)
> Line: 2 ▒Á#
> Line: 3 __libc_start_main
> Line: 4 (null) Segmentation fault (core dumped)

.c 文件的片段

void ReadWords(struct assem item)               //reads words into array    
{
char *word;
for(int s = 0; s < item.counter; s++)
{
item.word = strtok(item.myLines[s], " ");
item.myWord[s] = item.word;
}
}

void printWords(struct assem item)
{
for(int s = 0; s < item.counter; s++)
{
printf("Line: %i %s\n", s , item.myWord[s]);
}
}

.h 文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct assem
{
char myString[101]; //buffer
char *myLines[20]; //this will store the lines from a text file..up to 20 lines
char *myWord[20];
char *word;
int counter; //counter for number of lines
//printing stuff...prints file directly from whats STORED IN THE ARRAY

};

int readFile(FILE *FileToBeRead, struct assem *item); //takes in the file that needs to be read and splits it into lines
void ReadWords(struct assem item); //stores the first word of each line in an array for evaluation
void printFile(struct assem item); //prints some stuff
int firstCheck(struct assem item);
void printWords(struct assem item); //checks the first character if its instruction, label, or comment

最佳答案

您的函数ReadWords应该用数据填充结构。它的签名是:

void ReadWords(struct assem item);

在这里,item是结构的本地副本,因为结构是按值传递的。函数返回后,对此局部结构的所有更改都会丢失,并且原始结构不会被初始化。 (因此您在打印时会看到垃圾值。)

您可以通过传递指向结构的指针来解决此问题:

void ReadWords(struct assem *item) 
{
item->word = ...;
}

这样调用它:

struct assem item;

ReadWords(&item);

另一种可能性是让函数返回一个结构:

struct assem ReadWords()
{
struct assem item;

item.word = ...;
// ...
return item;
}

并这样调用它:

struct assem item = ReadWord();

不过,按值将结构传递给打印函数是可以的,因为打印时不会修改原始结构。如果结构很大,您还可以考虑将其作为 const struct assem * 传递。然而,const 指针可以避免复制。 (返回结构体也有同样的问题,所以更喜欢指针。)

最后,我认为您不需要使用结构成员进行标记化。 item.word应该是什么意思是在解析了 te 行之后吗?

关于C:数组元素消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31604559/

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