This program is printing weird. Can anyone help me how to fix it?
Code:#include <stdio.h> int main(void) { int a [ ] = {0, 2, 4, 6, 8}, *p = a + 3; printf("%s%d%s\n%s%d%s\n") "a[?] = ", *p, "?", "a[?+1] = ", *p + 1, "?"); return 0; }
This program is printing weird. Can anyone help me how to fix it?
Code:#include <stdio.h> int main(void) { int a [ ] = {0, 2, 4, 6, 8}, *p = a + 3; printf("%s%d%s\n%s%d%s\n") "a[?] = ", *p, "?", "a[?+1] = ", *p + 1, "?"); return 0; }
LOL....well its a lab for class and when it prints, it prints weird.
I am even surprise it prints for you at all.
There's no string in your array of type int called a. All of those are single integers in army formation , thus you can not pass a %s to printf at all.Code:printf("%s%d%s\n%s%d%s\n") /* what's that ) there? */
About these:
No idea what they are. I suppose you were trying to do some assignments and using them as part of the printf arguments, but it doesn't work like that.Code:"a[?] = ", *p, "?", "a[?+1] = ", *p + 1, "?");
Last edited by Aia; 02-04-2008 at 07:15 PM.
When the eagles are silent, the parrots begin to jabber. ~Winston Churchill
Yea It acutally compiles....but when it prints...it prints part of the code.
This is what it prints:
a[?] = 6?
a[?+1] = 7?
Amazing.
Assuming we take the extra parenthesis after \n"
The first %s is for the string "a[?] = "Code:printf("%s%d%s\n%s%d%s\n", "a[?] = ", *p, "?","a[?+1] = ", *p + 1, "?");
The first %d is for *p
The second %s is for "?"
Then a newline
The third %s is for "a[?+1] = "
The second %d is for *p + 1
and then it just display "?" as a literal string.
Don't ask me to go through that again
When the eagles are silent, the parrots begin to jabber. ~Winston Churchill
int* p - declares pointer to int
p = a+3 - makes pointer to point the 4th element of the array a which is 6
*p later retreives this element to print it
*p+1 - does the same, then adds one (getting 7) and prints the resulting value.
So your "weird" output is as expecting. It is just hard to understand due to messy coding style
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler