Why string assignment require new memory location?

Debojit Acharjee 435 Reputation points
2023-06-04T12:44:59.2233333+00:00

When any integer or a single character is assigned to a pointer, it uses the same memory location, but why a sting value is stored in different memory locations in every assignment?

IN the following program integer 30 and character 'c' takes the same memory location but why the string "C" and "D" takes different memory locations?

#include <stdio.h>

int main()

{

    char *c;

    *c = 30;
    printf("The memory location of 30 is: %x\n", c);

    *c = 'c';
    printf("The memory location of 'c' is: %x\n", c);

    c = "C";
    printf("The memory location of \"C\" is: %x\n", c);

    c = "D";
    printf("The memory location of \"D\" is: %x\n", c);

    return 0;
}

Output:

The memory location of 30 is: 265000

The memory location of 'c' is: 265000

The memory location of "C" is: 4050ab

The memory location of "D" is: 4050d3

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,878 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,632 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. didier bagarry 160 Reputation points
    2023-06-04T13:20:43.8533333+00:00

    Until the line c = "C"; the pointer c has no given values, so lines before are undefined behaviors! You try to write value at the address given by c.

    The address displayed before is the random value in c.

    After, your code displays c value which is the address of the array "C" then displays the address of the array "D". The strings "C" and "D" are string literals their have each a fixed address displayed by your code and their address is obviously different.

    A pointer is simply a variable which store an address, like an int can store a integral number. We can read or write where the c pointer points using a *. Nether try to do *c before having set c.

    1 person found this answer helpful.