Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String and pointer in C++

Tags:

c++

Below is the code for which I want to know the answer to 2 questions in the side comment. Please help me

#include<iostream>

using namespace std;

int main()
{
    char *p="Hello";
    cout <<*p;     //gives H
    cout <<*(p++); //also gives H.Why?
    cout <<*(p++); //gives e.
    cout <<*(p++); //gives l.
    cout <<*(p++); //gives l.
    cout <<*(p++); //gives o.
    cout <<*(p++); //gives no output.Why? It should give some garbage value!
}
like image 735
Naveen Avatar asked Nov 24 '25 08:11

Naveen


1 Answers

*(p++) gives 'h' because you first ask the value and than increment the position of your pointer and it the same thing in the last line.

like image 85
Engine Avatar answered Nov 26 '25 01:11

Engine