【发布时间】:2011-09-12 00:25:54
【问题描述】:
我有一些不确定数量的变量及其计数的排序数组。我需要像这样构建一个字符串:
Attribute[0]: p=2, e=8
我的问题是数组实际上是一个指针,我不想使用固定长度的循环,所以我看到的唯一解决方案是使用数组指针。
void printArray(Node_ptr node){
int count=0; //character count
char *temp= node->attributes; //duplicate attribute array
char cur; //current char
char *outputCat= emalloc(150); //concatenate counts to a single string
strcpy(outputCat, "Attribute %d counts are: ");
qsort(temp, lineCount, sizeof(char), compare); //sort the array
while ((temp) != NULL){
cur= *temp;
++temp;
if (strcmp(&cur, temp)==0) //if characters are same
count++;
else { //build reporting string
strcat(outputCat, &cur);
strcat(outputCat, "= ");
sprintf(outputCat, "%d ", count);
count=0;
}
}
free(outputCat);
}
这里的问题是strcmp(&cur, ++temp)==0 每次都返回 false,即使我在调试器中看到它们的值也是如此。正因为如此,else 条件不断被构建,并在多次迭代后引发段错误。
两个问题:
1- 即使输入相同的值,什么可以使strcmp 返回非零值?
2- 我可以做些什么来修复代码?
【问题讨论】:
-
您不应该在
char上使用strcmp或strcat。两个参数都必须是 NULL 终止的字符数组。这本身就可能导致段错误。事实上,如果修复它可以完全修复您的代码,我不会感到惊讶。 -
大脑放屁。我忘了字符可以直接比较,不用函数。然而,改变并没有做任何事情,因为比较总是被跳过,即使
cur是'e',*temp也是如此 -
好吧,这就是答案,不是吗?您应该重新提交作为答案,以便 Jason 可以接受。
-
更新您的代码,以便我们可以看到仍然无法正常工作的部分。
标签: c segmentation-fault strcmp