我有一个方法可以接收文件列表,并获取有关文件的数据。这些文件的格式作为两个一维数组返回。我想将它们组合成一个二维数组。
文件只返回一个类型数组和一个数据数组。
这是有问题的方法。我成功地将我需要的数据从文件中获取到一维数组中,但是当我尝试将它们添加到二维数组中时,它会运行(但会发出警告,指出 char * 和 char *[][] 不是吨当量)。
char *ParseFiles(char *listOfFiles[32])
{
char *allFileData;
char *tmpArray[32][32];
allFileData = tmpArray;
for(int i = 0; i < listOfFiles[i]; i++)
{
int j = 0;
// Get the File Type
char *currentFileType = GetFileType(listOfFiles[i], strlen(listOfFiles[i]));
if(currentFileType)
{
// Warning char * and char *[][] are not equivalent.
tmpArray[i][j] = currentFileType;
printf("File %d is %s\n", i, currentFileType);
//printf("File %d is %s\n", i, &tmpArray[i][j]);
//free(currentFileType);
}
//Get all File Data
// Warning char * and char *[][] are not equivalent.
char *currentFileData = GetFileData(listOfFiles[i]);
j = j + 1;
if(currentFileData)
{
tmpArray[i][j] = currentFileData;
printf("File Data:\n%s\n", currentFileData);
//free(currentFileType);
}
}
return allFileData;
}
当我尝试在被注释掉的 printf 语句中输出 tmpArray[][]
值时,我得到了意想不到的字符(对于犯错的人来说是意想不到的)?] p
问题是基于两个 char 数组不是同一类型的警告,还是因为我试图将一维数组错误地插入到多维数组中?
我收到的确切警告是 warning: incompatible pointer types assigning to 'char* from 'char *[32][32]'
下面是我的其他两种方法,以及我的主要方法:
char *GetFileType(char *filePath, int size)
{
char *ret = malloc(size);
char currentLine[100];
FILE *file = fopen(filePath, "r");
while(fgets(currentLine, sizeof(currentLine), file) != NULL)
{
if(strstr(currentLine, "test"))
{
ret = "test";
}
else if(strstr(currentLine, "production"))
{
ret = "production";
}
}
if(!ret)
{
return NULL;
}
return ret;
}
char *GetFileData(char *filePath)
{
char *buffer = NULL;
size_t size = 0;
FILE *file = fopen(filePath, "r");
// Get the buffer size
fseek(file, 0, SEEK_END);
size = ftell(file);
// Reset the position of the stream
rewind(file);
buffer = malloc((size + 1) * sizeof(*buffer));
// Read the entire file into the buffer
fread(buffer, size, 1, file);
buffer[size] = '\0';
return buffer;
}
int main (void)
{
char *listOfFiles[32] = {"file1.txt", "file2.txt", "file3.txt"};
ParseFiles(listOfFiles);
printf("Press ENTER key to Continue");
getchar();
return 0;
}
最佳答案
问题不在你说的地方,而是在这里:
char *allFileData;
char *tmpArray[32][32];
allFileData = tmpArray;
tmpArray
的类型是char *[32][32]
。 allFileData
的类型是char *
。分配根本无效。
还有一件更糟糕的事情发生了:您返回了指向局部变量 tmpArray
的allFileData
。一旦函数返回,变量tmpArray
将超出作用域,您返回的指针将立即失效。要么将数组作为参数传入,要么在函数内部动态分配它。
关于c - 如何将数组存储在 MD 数组中,并从函数返回该数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50380643/