I have a sorted array of some indeterminate number of variables and counts thereof. I need to build a string like so:
Attribute[0]: p=2, e=8
My issue is the array is actually a pointer, and I don’t want to use a loop of fixed length, so the only solution I see is to use an array pointer.
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);
}
The issue here is strcmp(&cur, ++temp)==0 is returning false every time, even when I see their values in the debugger. Because of this, the else conditional is constantly being built up and throws a segfault after a number of iterations.
Two questions:
1- What can make strcmp return non-zero even when identical values are entered?
2- What can I do to fix the code?
In your line:
curis achardeclared locally, and therefore,&curis just some location on the stack, and rather meaningless in this context.I believe you mean to check if the current-character
curis the same as the next character*temp.This would look like:
Next, I would look at massively simplify your output section:
And finally, I doubt your loop will ever terminate, as it continues to do
temp++, whiletemp != NULL.I believe you intend to check the VALUE stored at the pointer
temp.*tempshould be properly checked against ‘\0’, instead of NULL.(\0 and NULL happen to have the same value, but they should not be treated the same semantically)
P.S. Your simple, but excellent comment “// if characters are same” was extremely helpful for me to understand your code. This is an excellent case of short, meaningful comments being INVALUABLE. Thank you.
(Hopefully final edit)
In total, the changes I recommend look like:
How’s that work out for you?