c语言strcpy错误,C语言中的Printf和Strcpy错误。
Here i wrote a piece of code. A function to add long numbers (used strings to represent numbers).
這里我寫了一段代碼。添加長數字的函數(使用字符串表示數字)。
I want to know about two bugs that I usually face while coding in C
我想知道在C編碼時我通常會面對的兩個錯誤。
About printf statements , sometimes upon removing some printf statements i get logical errors but on putting them back the code runs perfectly. I dont understand why and do let me know how to avoid those errors too.
關于printf語句,有時在刪除一些printf語句時,我得到了邏輯錯誤,但是在將它們放回代碼時,代碼運行得很好。我不明白為什么,也一定要讓我知道如何避免這些錯誤。
Eg. In below code, the line mentioned in code (comments specified too infront of that line) after commenting it back or removing it, "Answer" variable receives blank string(case 1) and uncommenting it back gives correct output(case 2)
如。在下面的代碼中,代碼中所提到的行(在該行前面指定的注釋)在注釋掉它或刪除它之后,“回答”變量會接收到空白字符串(情況1),并取消注釋,給出正確的輸出(情況2)
About strcpy function, what is the bug or analogy in it that it behaves wierd sometimes
關于strcpy函數,它的bug或類比是什么,它有時表現得很糟糕。
Eg. In above mentioned case 2, even though the "add" function is returning correct output why is it not getting copied correctly into the "Answer" variable.
如。在上面提到的情形2中,即使“add”函數返回正確的輸出,為什么它不能正確地復制到“應答”變量中。
Code is here
代碼在這里
#include
#include
char *strrev(char *str)
{
char *p1, *p2;
if (! str || ! *str)
return str;
for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
{
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}
return str;
}
char* add(char a[],char b[]){
int n1=strlen(a);
int n2=strlen(b);
char c[20],d[20];
int i,j,k=0,carry=0,sum=0;
for(i=n1-1,j=n2-1;i>=0 && j>=0;i--,j--){
sum = (a[i]-'0')+(b[j]-'0')+carry;
c[k++]=sum%10 + '0';
carry=sum/10;
}
if(i>=0){
for(;i>=0;i--){
sum = (a[i]-'0')+carry;
c[k++]=sum%10 + '0';
carry=sum/10;
}
}
else if(j>=0){
for(;j>=0;j--){
sum = (b[j]-'0')+carry;
c[k++]=sum%10 +'0';
carry=sum/10;
}
}
if(carry){
while(carry){
c[k++]=carry%10 + '0';
carry/=10;
}
}
c[k]='\0';
printf("\nResult under function = %s",strrev(c)); //upon removing this printf statement the Result variable in main() receives a blank string
return strrev(c);
}
int main(){
char answer[20];
printf("\nAnswer = %s\n",add("0","1"));
strcpy(answer,add("0","1"));
printf("\nNow Answer is %s \n",answer); // Here is the bug
return 0;
}
1 個解決方案
#1
3
You have undefined behavior because you return a pointer to a local variable. The array c in the add function will go out of scope once the function returns, leaving you with a stray pointer.
您有未定義的行為,因為您返回一個指向局部變量的指針。當函數返回時,add函數中的數組c將超出范圍,留給您一個離散指針。
總結
以上是生活随笔為你收集整理的c语言strcpy错误,C语言中的Printf和Strcpy错误。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 纯c语言贪吃蛇,纯C语言贪吃蛇 求助
- 下一篇: c语言链表把多少分以上打出来,大神帮我看