question about vc++.net compiler

N

nick

#include <stdio.h>

#include <string.h>
int main(void)
{
char message[]="Welcome to C Programming!";
char *cptr;
cptr = message + 5;
printf("%c\n", cptr);
return 0;
}

the above code, when i put it in VC++.NET, it can't display properly.
but when i put it in MinGW Developer Studio, it can show the result 'm'.
why?

thanks!
 
M

Mike Wahler

nick said:
#include <stdio.h>

#include <string.h>
int main(void)
{
char message[]="Welcome to C Programming!";
char *cptr;
cptr = message + 5;
printf("%c\n", cptr);
return 0;
}

the above code, when i put it in VC++.NET, it can't display properly.

There is no 'properly'. The behavior is undefined.
%c is for type 'char' not 'char*'.

Perhaps you meant:
printf("%c\n", *cptr);
but when i put it in MinGW Developer Studio, it can show the result 'm'.
why?

Undefined behavior can be manifest as anything.

-Mike
 
M

Mark McIntyre

#include <stdio.h>

#include <string.h>
int main(void)
{
char message[]="Welcome to C Programming!";
char *cptr;
cptr = message + 5;
printf("%c\n", cptr);
return 0;
}

the above code, when i put it in VC++.NET, it can't display properly.
but when i put it in MinGW Developer Studio, it can show the result 'm'.
why?

%c prints a character. The 5th character of message is 'm' which is
presumably what you were expecting.

However cptr is a pointer. Printing the pointer with %c is undefined
behaviour, and the result could be anything (often it will be the
value of the address, converted to a char). So, if you got 'm' on
Mingw, it was coincidence.

Change the printf to *cptr, to get the value stored at cptr.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top