I understand this is part of the basic stuff, but i am stuck :-( Can someone please help me?
Program 1:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a=1,b=2,c;
c=(a+b)++;
}
Why is the output an error? lvalue required?
Program 2:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *p1="name";
char *p2;
p2=(char*)malloc(20);
memset(p2,0,20);
while(*p2++=*p1++);
printf("%s\n",p2);
}
Why is the output, an empty string? And if i reverse the order of increment, that is: while(++*p2=++*p1);
, why the lvalue error comes?
For the first question,(a+b)++
means "increment the value of a+b
by 1".
You cannot increment a+b
, though, for it's not a variable. What would you expect to happen in the following code?
int a = 1, b = 2;
printf("a = %d, b = %d, a+b = %d\n", a, b, a+b);
(a+b)++;
printf("a = %d, b = %d, a+b = %d\n", a, b, a+b);
Clearly the first printf
should print
a = 1, b = 2, a+b = 3
But what about the second one?
a = ?, b = ?, a+b = 4
It's not clear what a or b should be if we increment the sum.
As for the second question, remember that you're changing p2
when you copy over the data, so when you ask to print out what it's pointing at, it's pointing at the end of the string, not the beginning.
An easier way to do the string copy would be to use strcpy
, like so:
strcpy(p2, p1);
Note, this is only safe because you know that the size of the string in p1
isn't greater than the size of p2
. If you're not sure about the size of the string (for instance, if you get the string from user input), you'll need to be careful, as is outlined on Wikipedia.
As for why while(++*p2=++*p1);
doesn't work, while while(*p2++=*p1++);
does:
Postfix-++
has higher precedence than *
. This means, *p2++
means *(p2++)
.
So
*(p2++) = something;
is the same as
*p2 = something;
p2 += 1;
Meanwhile, ++*p2
means ++(*p2)
, or "whatever p2
points to, incremented by one".
Again, you get the problem, if you say:
int a = 5, *p2 = &a;
++*p2 = 10;
printf("a = %d\n", a);
What would you expect this to print? If anything, it should print 9, because you're telling the compiler that *p2+1 = 10
.
You can't expect a C-compiler to solve that equation, however, so in order to keep the language simple and efficient, this sort of thing is forbidden.