« Characters arrays and character pointers

Understand Characters arrays and character pointers

Character arrays

1int arr[] = {1, 2, 3};
2char ch[] = "abc";
3cout << "arr: " << arr << endl;
4cout << "ch: " << ch << endl;

cout is implemented differently for characters arrays and character pointers. It will go to the location and will start printing characters till it visits '\0' null character.

1cout << "&ch: " << &ch << endl;

This will actually give the address of the character array

Character Pointers

1char *c = &ch[0];
2cout << "c: " << c << endl;

This will also print characters until it visits '\0' null character as c is a character pointer.

1char c1 = 'a';
2char *pc = &c1;
3cout << "c1: " << c1 << endl;
4cout << "pc: " << pc << endl;

As a is not a string but a character so there won't be a \0 character at the end like a string. c1 is a char so it will just print a. pc being a character pointer will start printing garbage characters until it visits \0 null character.

1char str[] = "abcde"; // String literal

In case of string literals, first temp memory is created to store abcde. Then array is allocated memory and data is copied into it.

string_literal.jpg

1char *pstr = "abcde";

Here pointer is pointing to read-only temp memory. It may or may not crash when we try to change it, which is worse. So we should not use this approach.

Final Code

1#include <iostream>
2#include <iomanip>
3#include <algorithm>
4#include <string>
5#include <cstring>
6#include <vector>
7#include <cmath>
8#include <map>
9#include <climits>
10// climits for INT_MIN
11#include <unordered_map>
12using namespace std;
13int main()
14{
15 int arr[] = {1, 2, 3};
16 char ch[] = "abc"; // abc being a string last character is \0 null character
17
18 cout << "arr: " << arr << endl;
19 cout << "ch: " << ch << endl;
20
21 cout << "&ch: " << &ch << endl;
22 // This will actually give the location of character array
23
24 char *c = &ch[0];
25 cout << "c: " << c << endl;
26
27 char c1 = 'a';
28 char *pc = &c1;
29
30 cout << "c1: " << c1 << endl;
31 cout << "pc: " << pc << endl;
32 // This will start printing characters until it visits '\0' null character
33
34 char str[] = "abcde";
35 // String literal
36
37 char *pstr = "abcde";
38 // So We should not use this approach.
39 return 0;
40}