[英]Printing out values using pointers
我有一些不確定數量的變量和計數的排序數組。 我需要像這樣構建一個字符串:
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-如何修復代碼?
在你的行:
strcmp(&cur, temp)
cur
是在本地聲明的char
,因此, &cur
只是堆棧中的某個位置,在此上下文中相當無意義。
我相信你的意思是檢查當前字符cur
是否與下一個字符*temp
。
這看起來像:
if (cur == *temp) //if characters are same
count++;
接下來,我將大量簡化您的輸出部分:
sprintf(outputCat, "%c = %d", *cur, count); // e.g. "e = 8"
count=0;
最后,我懷疑你的循環將永遠終止,因為它繼續執行temp++
,而temp != NULL
。
我相信你打算檢查存儲在指針temp
的VALUE。
*temp
應該針對'\\ 0'正確檢查,而不是NULL。
(\\ 0和NULL碰巧有相同的價值,但他們不應該在語義上同等對待)
while (*temp != '\0'){
PS你簡單而優秀的評論“//如果字符相同”對我理解你的代碼非常有幫助。 這是一個很好的案例,簡短而有意義的評論是不可能的 。 謝謝。
(希望最終編輯)
總的來說,我推薦的變化如下:
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 != '\0'){
cur= *temp;
++temp;
if (cur == *temp) //if characters are same
count++;
else { //build reporting string
sprintf(outputCat, "%c = %d", *cur, count); // e.g. "e = 8"
count=0;
}
}
free(outputCat);
}
這對你有什么影響?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.