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
- 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.
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)
- About strcpy function, what is the bug or analogy in it that it behaves wierd sometimes
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.
Code is here
#include<stdio.h>
#include<string.h>
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;
}