我试图用 C 语言编写一个简短的程序,该程序从标准输入中获取空格分隔的标记,对标记进行洗牌(置换),然后将洗牌标记打印到标准输出。我的洗牌算法工作正常,问题在于令牌解析。我想将标记存储在动态字符串数组中,以便程序可以支持通过标准输入传递任意数量的标记。但是,每当需要扩展数组时,我当前的动态数组实现都会导致分段错误。我做错了什么?
我的代码:
#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