Pointers and Strings in C

In this class, we will try to understand Pointers and Strings in C.

Pointers and Strings in C

We already had our discussion on pointers and strings.

Pointers and Strings

We will try to understand the concept of pointers and strings using the programming example below.

Pointers and Strings in C
Pointers and Strings in C Example

In the above example, the first two lines of code create the strings c and c1, as shown below.

Pointers and Strings in C First and Second Line
Pointers and Strings in C First and Second Line

We have created a pointer p to the string in the third line of code, as shown below.

Pointers and Strings in C Third Line
Third Line

The pointer to a string is created as similar to the ‘string,’ we can access the elements of the string pointer, but we can not modify the ‘elements’ of the string pointer.

In the fourth line of code, the pointer variable q will be pointing to the string c1.

Pointers and Strings in C Fourth Line
Fourth Line

Now the string pointer is not a string constant.

The fifth and sixth lines of code modify the third element of the string c and q to H, respectively.

The seventh, eighth, and ninth lines of code are printing the strings c, p, and q as LeaHning, Welcome!, and MonHey.

The tenth line of code is essential to understand because we are trying to modify the string pointer.

The modification of the string pointer is NOT possible.

So, the compiler will produce a run time error and has undefined behavior.

On our compiler, the compiler will NOT execute the lines below it.