DR. SABUZ
DR. SABUZ

Reputation: 19

How does a pointer works when it assigns directly to a string without pointing to any variable?

 int main() 
    {
      char *name="Shakib Al Hasan"; 
      printf("My name is %s\r\n",name) ;

      return 0;
     }

These codes work nicely. As we all know a pointer should be pointed to another variable of same data type before use.But in this case there is no other variable declared and assigned. My question is how it works?

Upvotes: 0

Views: 75

Answers (3)

user6662513
user6662513

Reputation:

When you save a pointer to a string, put a string in the "random memory addresses." The meaning is the same as when I order a book from Amazon. I request them to be delivered to my home to the Amazon Web Services site. I have to come to my house to take it directly from the deliveryman. So, I leave my home address on the Amazon website services That's just a memory address.

char * string = "hello"; This is an example. This does not give the direct meaning of "hello" to the deliveryman. So I give the "string" is a string variable in "random memory address" of "hello".

  • All variables are specified in the interim when the program is executed, a random address memory. It's not merely is invisible to the programmer.
  • All variables used by the specified size in bytes of memory space.

In fact, I'm not perfect, and I'm still in learning process. My information also is not 100% perfect. If there is an error in my Answer, or incorrect translation, Give me comments.

Upvotes: 0

eRaisedToX
eRaisedToX

Reputation: 3361

As we all know a pointer should be pointed to another variable of same data type before use

Correct ...

... but pls note that pointer does not mean pointer points to a variable.

Actually a pointer points to a memory location containing data of same type (ie the same type as of pointer).

Hence, here name, which is a pointer, is pointing to the starting address of a read-only memory location which contains string "Shakib Al Hasan" (essentially a char array). And it is being printed using the %s format specifier and passing starting address of that pointer called name.

Upvotes: 1

aschepler
aschepler

Reputation: 72271

A string literal acts as though you had a static const array of characters. The actual array is created by the compiler. So your code is almost equivalent to

int main() 
{
    static const char name_literal[] = "Shakib Al Hasan";
    char *name= (char*) name_literal; 
    printf("My name is %s\r\n",name) ;

    return 0;
}

(One slight difference: you don't get a guarantee that name_literal is at a different address from all other objects.)

Upvotes: 2

Related Questions