[C] Pointers – Pointers and Arrays

Pointers and Arrays are quite similar in C. In many cases, they are even interchangeable. But they differ slightly in some cases. Let’s delve into them.

1. Pointers and Arrays

When you define an array, the variable name acts like an pointer to the first element of the array. It is quite interesting feature in C.

Think about strings in C. In C, a string is just an array of characters.

```char greeting[] = "Hello, World";
char *p = greeting;
printf("%s n", p); /* Hello, World */
printf("%c n", *p); /* H */
*(p+1) = 'E';
printf("%s n", p); /* HEllo, World */
printf("%s n", p+7); /* World */
```

By using a pointer, you can manipulate an array in diverse ways.

2. Arrays to Pointers

The name of an array can be used like a pointer to the first element.

```char greeting[] = "Hello, World";

printf("%c n", greeting[1]); /* e */
printf("%c n", *greeting); /* H */
printf("%c n", *(greeting+1)); /* e */
```

3.  Pointers to Arrays

You can even use a pointer variable as an array variable.

```char greeting[] = "Hello, World";
char *p = greeting;

printf("%c n", p[0]); /* H */
printf("%c n", p[1]); /* e */
printf("%c n", *(p+1)); /* e */
```

4. sizeof Operator

So are a pointer and an array the same? Let’s use the “sizeof” operator.

```char greeting[] = "Hello, World";
char *p = greeting;

printf("%i n", sizeof(greeting)); /* 13 = 12 + '\0' */
printf("%i n", sizeof(p)); /* 4 or 8 */
printf("%i n", sizeof(*p)); /* 1 = sizeof(char) */
```

C compiler smartly calculates the whole size of an array. But it does not work when you use a pointer. It just returns the size of the memory address.

5. Immutable Strings

There is another difference when you deal with a string as an array and as a pointer.

```char greeting[] = "Hello, World";
char *p = "Hello, World";
```

Can you spot the difference between two?

```printf("%c n", greeting[1]);
printf("%c n", p[1]);
printf("%c n", *(greeting+1));
printf("%c n", *(p+1));
```

When you read a value from them, they work identically. What if you want to modify the string?

```greeting[1] = 'E';
printf("%c n", greeting[1]);
p[1] = 'E'; /* error */
printf("%c n", p[1]);
```

You can compile the code but it will crash at runtime. You can modify character in the array but cannot do it through the pointer.

The reason is when you create an array, the string is located in the stack. But when you use a pointer to a string literal, it points directly to the address of a string literal. In all most machines, a string literal regarded as a constant and cannot be modified.