Character Array and Character Pointer in C

In this chapter, we will study the difference between character array and character pointer.

Consider the following example:

Can you point out similarities or differences between them ?

The similarity is:

The type of both the variables is a pointer to char or (char*), so you can pass either of them to a function whose formal argument accepts an array of characters or a character pointer.

Here are the differences:

  1. arr is an array of 12 characters. When compiler sees the statement:

    It allocates 12 consecutive bytes of memory and associates the address of the first allocated byte with arr.

    character-array-in-memory

    On the other hand when the compiler sees the statement.

    It allocates 12 consecutive bytes for string literal "Hello World" and 4 extra bytes for pointer variable ptr. And assigns the address of the string literal to ptr. So, in this case, a total of 14 bytes are allocated.

    character-pointer-and-string-literal

  2. We already learned that name of the array is a constant pointer. So if arr points to the address 2000, until the program ends it will always point to the address 2000, we can’t change its address. This means string assignment is not valid for strings defined as arrays.

    On the contrary, ptr is a pointer variable of type char, so it can take any other address. As a result string, assignments are valid for pointers.

    string-assignment-is-valid-for-pointer-to-char
    After the above assignment, ptr points to the address of "Yellow World" which is stored somewhere in the memory.

    Obviously, the question arises so how do we assign a different string to arr ?

    We can assign a new string to arr by using gets(), scanf(), strcpy() or by assigning characters one by one.

  3. Recall that modifying a string literal causes undefined behavior, so the following operations are invalid.

  4. Using an uninitialized pointer may also lead to undefined undefined behavior.

    Here ptr is uninitialized an contains garbage value. So the following operations are invalid.

    We can only use ptr only if it points to a valid memory location.

    Now all the operations mentioned above are valid. Another way we can use ptr is by allocation memory dynamically using malloc() or calloc() functions.

Let’s conclude this chapter by creating dynamic 1-d array of characters.

Expected Output:

4 thoughts on “Character Array and Character Pointer in C

    • Poniter is used to point address of its data type(like int pointer will point to intiger data type and char pointer will point to char data type).

  1. should ptr from: char ptr* = “Yello World” only store an additional byte, since ptr is of type char. You said it’s an additional 4 bytes.;

Leave a Comment