Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C and C++ difference behavior [closed]

Tags:

c++

c

I have created two template project in Eclipse with CDT plugin(one is C project, another C++), and have compiled two very similar projects(as for me) but I get absolutely different console outputs. Why this outputs 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;
}

output some garbage

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

like image 978
user2201747 Avatar asked Nov 27 '22 23:11

user2201747


1 Answers

You are printing int as char in C.

Change

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

to

printf("%d ",numbers[n]);
like image 91
Rohan Avatar answered Nov 29 '22 13:11

Rohan