0

I am novice in programming. I have written a program and confused in concepts of pointers.

#include <bits/stdc++.h>
using namespace std;
int main()
{
    char c[]="hello";
    char *a=c;
    cout<<a<<endl;
    int arr[]={1,2,3,5};
    int *p=arr;
    cout<<p<<endl;
    return 0;
}

When I print a, it prints hello but when I print p it print the address. Why?

BLUEPIXY
  • 38,201
  • 6
  • 29
  • 68
  • 2
    First of all, do you know which language you are actually trying to learn here? – Eugene Sh. Sep 28 '17 at 17:26
  • @AbhishekShukla Dude its c++ – ssovukluk Sep 28 '17 at 17:28
  • So you should rethink it, as it is not C. – Eugene Sh. Sep 28 '17 at 17:28
  • 1
    The `` is an invalid header for C. It is a compiler specific header for C++ and should not be used. – Thomas Matthews Sep 28 '17 at 17:28
  • If it is C my whole life is lie :((( – ssovukluk Sep 28 '17 at 17:29
  • Regarding `#include `, [this is bad form.](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) Worse, combined with `using namespace std;`, the entire standard library is included and pulled into the global namespace. This can result in a minefield of identifiers that can collide with what you define in your code resulting in some very hard to interpret mystery errors. It is unlikely to bite in trivial code like this, but when it does, wowzers. – user4581301 Sep 28 '17 at 17:35

1 Answers1

3

std::ostream has overload for const char* to display C-string.
int* would use the void* one which print the address.

Jarod42
  • 173,454
  • 13
  • 146
  • 250
  • with printf, it gives same result. – Abhishek Shukla Sep 28 '17 at 17:29
  • Which format do you use ? and BTW, one question by question (and `printf` would suit more with C tag). – Jarod42 Sep 28 '17 at 17:31
  • `#include using namespace std; int main(int argc, char const *argv[]) { char c[]="hello"; char *a=c; printf("%s\n",a); int arr[]={1,2,3,5}; int *p=arr; cout<

    – Abhishek Shukla Sep 28 '17 at 17:32
  • @AbhishekShukla `%s` tells `printf` that the variable is a null-terminated char array and is to be printed as one would a string. You said print a string, you provided a string, the program printed a string. Look at the `printf` documentation for the `%p` format specifier if you want to print the address of the array. Side note: Because `printf` doesn't know what the type of the provided variables are, you can pass it an integer and it will attempt to interpret it as a pointer to a `char` array and print it as a string to not-so-comical results. – user4581301 Sep 28 '17 at 17:44