【发布时间】:2017-04-06 07:57:43
【问题描述】:
我昨晚一直在调试这段小代码。我有两个数据文本文件,都包含 18000 个字符。我想将这 18000 个拆分为两个子字符串,每个子字符串 100 个字符,这样可以进行 180 次迭代。
棘手的是,在前 180 次迭代中,两个子字符串的大小都很好。 18次迭代后,子串的大小为0。
两个文件均已正确打开。我可以打印它们等等。我试图以我能想到的所有可能的方式分配子字符串,但到目前为止找不到解决方案。
int main(int argc, char const *argv[]) {
//Ive loaded two files into two strings buff1 and buff2 both size of 18000 chars
//It works fine with small data example, I dunno why but eventually I have work with much more bigger data set
//Id like to divide them into 100 char long pieces and do some stuff with that
char *substrA; //substring for buff1
char *substrB; //substring for buff2
substrA = malloc((wlen+1)*sizeof(char)); //word length wlen=100
substrA = malloc((wlen+1)*sizeof(char));
for (int i= 0; i <numOfSubProblems; ++i){ //numOfSubProblems = 18000/100
strncpy(substrA, buff1+i*wlen, wlen);
strncpy(substrB, buff2+i*wlen, wlen);
substrA[wlen] = '\0';
substrA[wlen] = '\0';
int lenA = strlen(substrA);
int lenB = strlen(substrB);
printf("STRA a STR B: %d %d \n",lenA,lenB);
DoSomething(substrA,substrB,i); //some parser and other functionality
}
return 0;
}
【问题讨论】:
-
subA和subB声明在哪里? -
用
strndup()代替malloc()+strncpy()怎么样? -
那么:有什么问题?