Assigning strings to pointer in C Language

19,168

Solution 1

  1. char *c; c="name";

    If you observe here, you are not assigning string "name" to variable c but, you are assigning the base address of memory where name is stored into variable c.

  2. The string name is stored in the string table created by the compiler, all the strings of this form are stored in string table, this string table is a const type, meaning you cannot write again to this location. e.g you can try these two lines char *p = "Hello" ; strcpy(p,"Hi");. While compilation you will get error at second line.

  3. int *c; c = 10;

    In the above code you are creating an integer pointer and assigning 10 to it, the compiler here understands that you are assigning 10 as an address. One more thing you need to understand is all the pointer variables store unsigned interger constants only. So even if it is char *c or int *c in both of these cases the variable c stores an unsigned integer only.

Solution 2

Strings in C are not native types. They are null-terminated char arrays. In your example,

char *c;
c="name";

The pointer c doesn't contain the content of the string itself, but rather the address of the string literal "name" ( to be more precise, the address of its first element).

Solution 3

At the level of the physical machine, they're the same. Just binary words of the appropriate width (usually 32 or 64). But C creates these two abstract types to help distinguish two separate uses of a machine word: holding a numeric (or symbolic) value vs. holding the address of another word (itself possibly a scalar (numeric) value or another pointer).

So pointers point to things, possibly other pointers. An it is important for readable C programming to distinguish these concepts firmly in the mind.

You can also violate these rules. But first you need to know what you're doing. :) how to explain what you're doing to other programmers (in your code comments).

The bytes of the "name" are allocated statically; that is, the bytes going into the object code produced by the compiler and into the executable program file. In the assignment c="name", "name" in the expression yields a pointer to (first of) the individual bytes, and the variable c (which is allocated dynamically since its an automatic variable, defined inside a function) receives this pointer as its "value".

c = *
    |
    V
  _____ _____ _____ _____ ______
  |'n'| |'a'| |'m'| |'e'| |'\0'|

In the integer example, you are setting the pointer to address 10. Whatever the tenth integer in memory is. The problem is that the very first page of memory is usually not mapped for your program. This allows the program to crash safely when it accesses a NULL pointer. To assign a value to the "value" pointed-at by the pointer is a two-step process. First the pointer must be set to point at some storage to hold the value. Commonly one uses malloc.

int *c = malloc(sizeof(int));

Then you may dereference the pointer and set and retrieve its associated value.

*c = 10;

With C99 compound literals, you can create automatic arrays which decay to pointers in expressions.

This is a pointer:

(int[3]){4, 5, 6}

This is the integer-string equivalent of char-string literals in C (with a slight difference in compiler semantics: the 4, 5, and 6 probably don't go in the string table but into a separate integer table).

Solution 4

char *c;
c="name";

This created a pointer and pointed it at a constant string. The compiler puts that in a part of memory that is marked as read-only.

it has no name and has static storage duration (meaning that it lives for the entire life of the program); and a variable of type pointer-to-char, called c, which is initialized with the location of the first character in that unnamed, read-only array.

If you declared it as c is global variables, then compiler place it on the data section of program directly. if you declared c as local variables then it is placed on stack,

Now for

int *c;
c=10;

here type of c is int *, which contains address of integer variables. see here for more explanation

Share:
19,168
Sudheer
Author by

Sudheer

Updated on June 25, 2022

Comments

  • Sudheer
    Sudheer over 1 year

    I am a new learner of C language, my question is about pointers. As far I learned and searched pointers can only store addresses of other variables, but cannot store the actual values(like integers or characters). But in the code below the char pointer c actually storing a string. It executes without errors and give the output as 'name'.

    #include <stdio.h>
    main()
    {
        char *c;
        c="name";
        puts(c);
    }
    

    can anyone explain how a pointer is storing a string without any memory or if memory is created where it is created and how much size it can be created.

    I tried using it with the integer type pointer

    #include <stdio.h>
    main()
    {
        int *c;
        c=10;
        printf("%d",c);
    }
    

    But it gave an error

    cc     test.c   -o test
    test.c: In function ‘main’:
    test.c:5:3: warning: assignment makes pointer from integer without a cast   [enabled by default]
    c=10;
    ^
    test.c:6:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
    printf("%d",c);
    ^
    

    Pointers stores the address of variable then why is integer pointer different from character pointer.

    If there is something I am missing about pointers plz explain.

    • ApproachingDarknessFish
      ApproachingDarknessFish over 9 years
      It's all just a matter of types. "name" is a pointer (technically an array) and can therefore be stored in a pointer. 10 is an integer and therefore cannot be stored in a pointer. I think your confusion stems from the not-so-obvious fact that string literals actually have pointer type.
  • David Grayson
    David Grayson over 9 years
    Yeah, when you write "name" that is a shortcut that tells the compiler to have some memory with the 4 letters of "name" followed by a null terminator, and lets you get a pointer to that string.
  • Sudheer
    Sudheer over 9 years
    where is the memory created won't it interfere with the other programs memory if i give a too long string
  • Yu Hao
    Yu Hao over 9 years
    @Sudheer It depends on the platform but string literals are usually stored in someplace read-only. I don't know why you think it would interfere with other programs.
  • Sudheer
    Sudheer over 9 years
    Thank you for your reply
  • unwind
    unwind over 9 years
    I don't think most compilers will warn for that strcpy() usage. It's of course absolutely correct to say that it's bad code (triggers undefined behavior) but I'm not sure compilers catch it.