C 在函数之间传递指向结构数组的指针
我有一个程序,它需要将一些文本逐字加载到数组中,因此我为中定义的每个文本都有一个结构 main.hC 在函数之间传递指向结构数组的指针,c,function,pointers,struct,C,Function,Pointers,Struct,我有一个程序,它需要将一些文本逐字加载到数组中,因此我为中定义的每个文本都有一个结构 main.h typedef struct wordTag{ char name[MAX_WORD]; char string[1000][MAX_WORD]; int words; }text; main.c void main(){ int fileCount = 0; text *checkTexts; fileCount = getCheckFiles(checkTexts);
typedef struct wordTag{
char name[MAX_WORD];
char string[1000][MAX_WORD];
int words;
}text;
main.c
void main(){
int fileCount = 0;
text *checkTexts;
fileCount = getCheckFiles(checkTexts);
for(i = 0; i < fileCount; i++){
printf("Tekst navn: %s\n", checkTexts[i].name);
}
}
void main(){
int fileCount=0;
文本*检查文本;
fileCount=getCheckFiles(checktext);
对于(i=0;i
文件.c
int getCheckFiles(text *checkTexts){
int fileCount, i;
FILE *file;
createFileList(&file);
fileCount = countFiles(file);
createArray(checkTexts, fileCount, file);
return fileCount;
}
void createArray(text *checkTexts, int fileCount, FILE *file){
int i, wordCount;
FILE *textFile;
text localText;
char fileName[MAX_WORD + 30];
checkTexts= (text *)malloc(fileCount * sizeof(text));
readFileNames(file, checkTexts);
for(i = 0; i < fileCount; i++){
localText = checkTexts[i];
strcpy(fileName, "./testFolder/");
strcat(fileName, localText.name);
openFile(&textFile, fileName);
localText.words = countWords(textFile);
readFileContent(textFile, localText);
checkTexts[i] = localText;
}
for(i = 0; i < fileCount; i++){
printf("Tekst navn: %s\n", checkTexts[i].name);
}
}
int getCheckFiles(text*checktext){
int fileCount,i;
文件*文件;
createFileList(文件(&F);
fileCount=countFiles(文件);
createArray(检查文本、文件计数、文件);
返回文件计数;
}
void createArray(text*checktext,int fileCount,FILE*FILE){
int i,字数;
文件*textFile;
文本本地文本;
字符文件名[MAX_WORD+30];
checktext=(text*)malloc(fileCount*sizeof(text));
读取文件名(文件、检查文本);
对于(i=0;i
现在,如果我在createArray函数中打印名称,一切正常,但是如果我尝试在我的主函数中打印,则会出现分段错误(内核转储)。您没有初始化您在
main()
中使用的checktext
指针
< C++(或C++)函数指针通过<强>值< /> >不被<强>引用< /强>(例外情况下,在C++中,当函数被声明为引用一个类型作为参数时)。因此,当调用getCheckFiles(checktext)
时,无论getCheckFiles()
如何处理传入的参数,它都不会更改main()
的checktext
变量
在调用
createArray()
时也会发生同样的事情。因此,尽管您在createArray()
中创建了数组,但指向malloc从未传播过的缓冲区的指针将不会返回调用链。问题在于createArray
中的malloc
调用不会将内存块与您提供的地址相关联(checktext
)正如您可能默认的那样,它提供了一个指向它保留的内存块的新指针。您提供的checktext
(内存地址)的值在createArray
中被覆盖<代码>检查文本也可以是局部变量。然而,当createArray
返回时,checktext
在main
中引用的仍然是旧的、未初始化的地址,并且该地址的内存(可能)与以前一样,即未分配或保留给其他人。因此,分段错误只是一个提示:学习gdb
,您就不必向任何人询问分段错误……您可以自己跟踪它,并准确地看到问题所在。。。