我试图用C编写一个简短的程序,该程序将stdin中的空格分隔的令牌吸收进来,对令牌进行改组(置换),然后将改组的令牌打印到stdout。我的改组算法工作正常,问题出在令牌解析上。我想将令牌存储在动态字符串数组中,以便程序可以支持通过stdin传递的任意数量的令牌。但是,我当前对动态数组的实现会在每当需要扩展数组时导致分段错误。我做错了什么?
我的代码:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 33
int main(int argc, char* argv[]) {
int i,j,k;
i=j=k=0;
int arrSize = 10;
/* Temp fix */
/* Get token count as command line argument */
//if (argc==2) { sscanf(argv[1],"%d",&arrSize); }
char c='\0';
char* t;
char** datArr = (char**)malloc(sizeof(char*)*arrSize);
//char* datArr[arrSize];
char token[BUFFERSIZE];
while ( (c=getc(stdin)) != EOF && c != '\0') {
if(isspace(c)) {
token[i] = '\0';
i=0;
if ( j >= arrSize) {
arrSize *= 2;
realloc(datArr, arrSize);
}
char* s = (char*)malloc(sizeof(char[BUFFERSIZE]));
strcpy(s,token);
datArr[j++] = s;
}
else if(i+1 < BUFFERSIZE) {
token[i++] = c;
}
}
/* Permutate & Print */
srand(time(NULL));
for(i=0;i<j;++i) {
k = rand()%(j-i);
t = datArr[k];
datArr[k] = datArr[j-i-1];
datArr[j-i-1] = t;
}
for(i=0;i<j;++i) { printf("%s ",datArr[i]); }
printf("\n");
return 0;
}
注意:我知道我确实释放了内存
一些示例输入(以使其为主题卡):
2C 3C 4C 5C 6C 7C 8C 9C 10C JC KC QC AC 2S 3S 4S 5S 6S 7S 8S 9S 10S JS KS QS AS
最佳答案
您是否尝试过测试:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 33
int main(int argc, char* argv[]) {
int i,j,k;
i=j=k=0;
int arrSize = 10;
/* Temp fix */
/* Get token count as command line argument */
//if (argc==2) { sscanf(argv[1],"%d",&arrSize); }
char c='\0';
char* t;
char** datArr = (char**)malloc(sizeof(char*)*arrSize);
//char* datArr[arrSize];
char token[BUFFERSIZE];
while ( (c=getc(stdin)) != EOF && c != '\0') {
// Just read the file
}
}
我认为这是一个无限循环。
getc()返回一个int而不是一个char,因此它永远都不应停止读取文件,这是一个无限循环。这将耗尽内存,并最终保证出现段错误。
我建议将
char c='\0';
更改为int c;
,然后从那里应用内存处理方面的改进。关于c - 如何在C中正确实现动态数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13223137/