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”函数返回正确的输出,为什么它不能正确地复制到“应答”变量中。

aHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9WZmdVTy5wbmc=

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将超出范围,留给您一个离散指针。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值