[英]Facing Issue in Reversing string in C without inbuilt libraries
我在不使用內置函數的情況下反轉 C 中的字符串時遇到問題:我在 Sublime Text 3 上使用 C 的 C89/C90 版本,我只是在我的代碼 output 中獲取字符數,但它沒有向我顯示反轉的字符串。
這是我的代碼:
#include<stdio.h>
int size_string(char a[]){
int count;
for(count=0;a[count]!='\0';count++);
return count;
}
void reverse(char *p,int size){
int i;char temp;
for(i=0;i<size/2;i++){
temp=*(p+i);
*(p+i)=*(p+size-i);
*(p+size-i)=temp;
}
}
int main(){
char a[45];int size;
printf("Enter a string : ");
fgets(a,sizeof(a),stdin);
size=size_string(a);
printf("%d\n",size);
reverse(a,size);
printf("%s",a);
return 0;
}
我收到此警告:
NumPyramid.c: In function 'size_string':
NumPyramid.c:4:2: warning: this 'for' clause does not guard... [-Wmisleading-indentation]
4 | for(count=0;a[count]!='\0';count++);
| ^~~
NumPyramid.c:5:3: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'for'
5 | return count;
| ^~~~~~
請注意,您還反轉了NUL
字節,將其放在字符串的開頭。 這導致printf1
在第一個字符 ( NUL
) 處終止。
從字符串末尾開始計算字節數時嘗試使用i+1
:
for(i=0;i<size/2;i++){
temp=*(p+i);
*(p+i)=*(p+size-(i+1));
*(p+size-(i+1))=temp;
}
編譯器警告您for
循環后的誤導性縮進。
這些行:
for(count=0;a[count]!='\0';count++);
return count;
誤導性地類似於(注意;
):
for(count=0;a[count]!='\0';count++)
return count;
但是這兩行的行為非常不同,一個版本在循環完成后返回。 另一個版本從循環內部返回。
這是一個樣式問題,可能會導致錯誤隱藏在眾目睽睽之下。
更好的格式是(注意縮進和;
在單獨的行中):
for(count=0;a[count]!='\0';count++)
;
return count;
因此,警告。 編譯器警告您確保看到這一行並且您確實寫了您想要寫的內容。
改變
reverse(a,size);
到
reverse(a,size-1);
基本上,您的反向字符串以 null 字節開頭,這就是它不打印任何內容的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.