IQOD #6

Posts 1–7 of 7 · Page 1 of 1
IQOD #6
Code:
void main()
{
      char *p;
      char buf[10] = {1,2,3,4,5,6,9,8};
      p = (buf+1)[5];
      printf("%d", p);
}
is there anything wrong with this code? If so, fix it and then whats the output? (remember, dont copy & paste in your compiler lol fix it 'on paper')

should move into the harder ones... these seem so trivial lol
Hmm lets see
<!--

it should be

p = (buf+6);
or
p = (buf+5);

because technically buf[5] means *(buf+5)
and you shouldn't try to assign buf[5] to p, because it wants an address, not the value pointed to by the address. And also p didn't point to an address yet, thus it would be a bad idea to try and assign a value to *p

and printf should be printf("%d", *p);

i should just show u the finished code

void main()
{
char *p;
char buf[10] = {1,2,3,4,5,6,9,8};
p = (buf+5); // or p = (buf+6);
printf("%d", *p);
}


and the output is 6, or 9 if you wanted buf+6


-->
what does it do?
Quote Originally Posted by Jimmy View Post
what does it do?
It doesn't do much. It is a test problem. It's for fun v_v
Wow 4,5,and 6! I haven't had a chance to get on my computer all day D: Ummm random guesses for all three: 3, George Washington, Missouri
Quote Originally Posted by B1ackAnge1 View Post
Code:
void main()
{
      char *p;
      char buf[10] = {1,2,3,4,5,6,9,8};
      p = (buf+1)[5];
      printf("%d", p);
}
is there anything wrong with this code? If so, fix it and then whats the output? (remember, dont copy & paste in your compiler lol fix it 'on paper')

should move into the harder ones... these seem so trivial lol
void main()
{
int *p = new int;
char buf[10] = {1,2,3,4,5,6,9,8};
p = (int*)(buf+1)[5];
printf("%d", p);
delete p;
}

output is 9.

p=(buf+1)[5]; would make p point to 0x000009(which isnt what we want i guess)
int *p = new int creates a pointer to a newly allocated int which then gets assigned 9(which is what we want) and delete the allocated memory afterwards
The problem with:
char* p = (buf+1)[5]; is that (buf+1)[5]; returns a 'char' and not a pointer
so indeed the fix is to either make char*p a char instead, or cast the right hand operand.
The value printed is '9' since buf+1[5] would be the same as buf[6];
Posts 1–7 of 7 · Page 1 of 1
This thread is closed for replies.

Similar Threads

Tags for this Thread

Talk with us