Array of Pointer - 2

Please explain the difference in the output of 2 programs
cout<<branch[i] in Program 1 gives output as
Architecture
Electrical
Computer
Civil

whereas

cout<<*branch[i] in Program 2 gives output as
A
E
C
C

Why? What is the logic behind *branch[i] giving only first character of each word as output and branch[i] giving full string as an output ?
1
2
3
4
5
6
7
8
9
10
11
//Program 1
#include<iostream>
using namespace std;
int main()
{
const char *branch[4] = { "Architecture", "Electrical", "Computer", "Civil" };
for (int i=0; i < 4; i++) 
cout<<branch[i]<<endl;
system("pause");
return 0;
}


1
2
3
4
5
6
7
8
9
10
11
//Program 2
#include<iostream>
using namespace std;
int main()
{
const char *branch[4] = { "Architecture", "Electrical", "Computer", "Civil" };
for (int i=0; i < 4; i++) 
cout<<*branch[i]<<endl;
system("pause");
return 0;
}

Last edited on
*branch[i] points to the beginning of your string instead of the whole string. You are dereferencing branch[i] and that points to the address which prints out just the first letter of your elements
branch[i] You are not dereferencing branch[i]. It goes through your string until it find a null terminating character and prints out the whole string.
Topic archived. No new replies allowed.