Difference behavior of C and C ++

I created two template projects in Eclipse with the CDT plugin (one is project C, the other is C ++) and compiled two very similar projects (as for me), but I get completely different console outputs. Why is this so different? C code:

#include <stdio.h> #include <stdlib.h> int main(void) { int numbers[5]; int * p; p = numbers; *p = 10; p++; *p = 20; p = &numbers[2]; *p = 30; p = numbers + 3; *p = 40; p = numbers; *(p+4) = 50; int n; for (n=0; n<5; n++) printf("%c ",numbers[n]); return EXIT_SUCCESS; } 

Exit some trash

C ++ Code:

 #include <iostream> using namespace std; int main() { int numbers[5]; int * p; p = numbers; *p = 10; p++; *p = 20; p = &numbers[2]; *p = 30; p = numbers + 3; *p = 40; p = numbers; *(p+4) = 50; for (int n=0; n<5; n++) cout << numbers[n] << " "; return 0; } 

Output

10, 20, 30, 40, 50

+4
source share
4 answers

You print int as char in C.

Edit

 printf("%c ",numbers[n]); 

to

 printf("%d ",numbers[n]); 
+23
source

You print the ASCII value of integers. Try

 printf("%i", numbers[n]) 

instead

 printf("%c", numbers[n]) 
+8
source

You are trying to print numbers as characters, causing an odd output. The code worked fine for me like this.

 #include <stdio.h> #include <stdlib.h> int main(void) { int numbers[5]; int * p; p = numbers; *p = 10; p++; *p = 20; p = &numbers[2]; *p = 30; p = numbers + 3; *p = 40; p = numbers; *(p+4) = 50; int n; for (n=0; n<5; n++) printf("%d ",numbers[n]); return EXIT_SUCCESS; } 

Pay attention to% d, not% c

+8
source

You need% d to print an integer and% c to print a char in C

http://www.cplusplus.com/reference/cstdio/printf/

Look at the expression below

 printf("%c ",numbers[n]); 

You use% c to print int, which is incorrect.

To be specific, printf was borrowed from C and has some limitations. The most common printf restriction mentioned is type safety, as it relies on the programmer to correctly match the format string with the arguments. The second limitation that comes back from the varargs environment is that you cannot extend the behavior with user-defined types. Printf knows how to print a set of types, and all that you choose from it. However, for some things for which it can be used, it is faster and easier to format lines with printf than with C ++ streams.

+1
source

All Articles