我正在尝试动态创建一个二维数组,然后打开一个 txt 文件并复制每个宽松的二维数组。然后将这个数组保存回我的 main.我一直遇到段错误。任何建议如何修复此代码? 顺便说一句,我认为问题在第二次 while 循环发生后出现...
#include<stdio.h>
char **randomArrayofStrings(){
char **twoArray=null;
int rows=50;
int col=20;
i=0;
FILE *file=null;
int messageSize=50;//this is number is trivial
file = fopen("somefile.txt","r");
twoArray= malloc(rows*sizeof(char*));
for(i=0;i<col;i++)
{
twoArray[i]=malloc(rows*sizeof(char));
strcpy(twoArray[i], "some random word");
}
while(!feof(file))
{
fgets(dArray[i],messageSize, file);
strtok(dArray[i], "\n");
i++;
}
return twoArray;
}
int main(int argc, char **argv)
{
char **localArray=null;
localArray=randomArrayofStrings();
for(i=0;i<20;i++)//20 is just a random number
printf("Strings: %s", localArray[i]);
}
最佳答案
如我所见,在您的函数中 randomArrayofStrings
循环 for
遍历代码中的“i cols”列。因此,您首先分配指针数组并将其视为 cols
,然后在循环中分配 rows
。
在 malloc
之后检查返回的值,如果在内存分配后它为 NULL,则不要使用该指针。
要释放分配的内存,请使用倒序 - 释放所有 rows
在循环中并且比免费cols
一次。例如:
for(i=0;i<col;i++){
free(twoArray[i]);
}
free(twoArray);
twoArray = NULL;
编辑:
还有,使用 malloc
和 free
你需要#include <stdlib.h>
, 和 #include <string.h>
对于 strcopy
, int i=0;
应该代替 i=0;
,指针的正确空值是 NULL
.
什么是dArray
?我没有看到声明或定义?你是说twoArray
?
编辑 2:
以下是我的程序版本:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **randomArrayofStrings(){
char **twoArray=NULL;
char * ptr = NULL;
int rows=50; // this will be also message size
int cols=20;
int i=0;
FILE *file=NULL;
file = fopen("somefile.txt","r");
if( file == NULL )
return NULL;
twoArray = (char**) malloc(cols * sizeof(char*));
if(twoArray == NULL)
{
return NULL;
}
for(i=0;i<cols;i++)
{
twoArray[i] = (char*)malloc(rows*sizeof(char));
if(twoArray[i] == NULL)
return NULL;
strcpy(twoArray[i], "some random word");
}
i = 0; // reset counter
while(!feof(file))
{
fgets(twoArray[i], rows, file);
ptr = strchr(twoArray[i],'\n');
if( ptr )
*ptr = '\0';
else
twoArray[i][rows-1] = '\0';
i++;
if( i >= cols)
break;
}
fclose(file);
return twoArray;
}
void freeMy2dArray(char **twoArray, int n)
{
int i;
for(i=0; i < n; i++){
free(twoArray[i]);
}
free(twoArray);
twoArray = NULL;
}
int main(int argc, char **argv)
{
int i;
char **localArray=NULL;
localArray = randomArrayofStrings();
if( localArray == NULL )
return 1;
for(i=0;i<20;i++)//20 is just a random number
printf("Strings: %s\n", localArray[i]);
freeMy2dArray(localArray, 20);
}
关于c - malloc 之后的 while 循环后出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29360946/