totally
totally

Reputation: 413

What is the point of initializing a string pointer in C

Here is my question. in C, i saw code like this:

char *s = "this is a string";

but then, s is not actually pointing to an actual memory right? and if you try to use s to modify the string, the result is undefined.

my question is, what is the point of assigning a string to the pointer then?

thanks.

Upvotes: 2

Views: 264

Answers (8)

Waqas Shabbir
Waqas Shabbir

Reputation: 753

In your case the pointer s is just pointing to the location that carries the first literal of the string. So if we want to change the string, it creates confusion as pointer s is pointing to the previous location. And if you want to change string using pointer, you should take care of the previous string's ending (i.e NULL).

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227518

s is not actually pointing to an actual memory right?

Technically, it is pointing to read-only memory. But the compiler is allowed to do whatever it wants as long as if follows the as-if rule. For example, if you never use s, it can be removed from your code completely.

Since it is read-only, any attempt to modify it is undefined behaviour. You can and should use const to indicate that the target of a pointer is immutable:

const char* s = "Hello const";

my question is, what is the point of assigning a string to the pointer then?

Just like storing a constant to any other type. You don't always need to modify strings. But you may want to pass a pointer to a string around to functions that don't care whether they point to a literal or to an array you own:

void foo(const char* str) { 
  // I won't modify the target of str. I don't care who owns it.
  printf("foo: %s", str);
}

void bar(const char* str) {}

char* a = "Hello, this is a literal";
char b[] = "Hello, this is a char array and I own it";

foo(a);
bar(a);
foo(b);

Upvotes: 1

user3386109
user3386109

Reputation: 34839

Everybody else has told you about the read-only memory and potential for undefined behavior if you attempt to modify the string, so I'll skip that part and answer the question, "what is the point of assigning a string to a pointer then?".

There are two reasons why

1) Just for brevity. After assigning the string to the pointer you can refer to the string as s instead of repeatedly typing "this is a string". This assumes of course that you intend to use the string in multiple function calls.

2) Because you may want to change the string that the pointer references. For example, in the following code, s is initialized assuming that the code will succeed, and is subsequently changed if there's a failure. At the end, the string that s points to is printed.

const char *s = "Yay, it worked!!!";

if ( openTheFile() == FAILED )
    s = "Dang, couldn't open the file";

else if ( readTheFile() == FAILED )
    s = "Oops, there's nothing in the file";

printf( "%s\n", s );

Note that const char * means that the string that s points to cannot be changed. It doesn't mean that s itself can't be changed.

Upvotes: 0

wefwefa3
wefwefa3

Reputation: 4036

By using const char * instead of a char [] the string will be stored in read only memory space. This allows the compiler to eliminate string duplication.

Try running this program:

#include <stdio.h>

int main()
{
    const char *s1 = "This is a string";
    const char *s2 = "This is a string";
    if (s1 == s2) {
        puts("s1 == s2");
    } else {
        puts("s1 != s2");
    }
}

For the me it outputs s1 == s2 which means that the string pointers point to the same memory location.

Now try replacing const char * with char []:

int main()
{
    const char s1[] = "This is a string";
    const char s2[] = "This is a string";
    if (s1 == s2) {
        puts("s1 == s2");
    } else {
        puts("s1 != s2");
    }
}

This outputs s1 != s2 which means that the compiler had to duplicate the string memory.

By using char * instead of char [] the compiler can do these optimizations that will decrease the size of you executable file.

Also note that you should not use char *s = "string". You should use const char *s = "string" instead. char *s is deprecated and unsafe. By using const char * you avoid the mistake of passing the string to a function that tries to modify the string.

Upvotes: 1

Abhineet
Abhineet

Reputation: 5409

When you do a char *s = "this is a string";, the memory is automatically allocated and populated with this string and a pointer to that memory is returned back to the caller (you). So, you do not need to explicitly put the string to some memory.

s is not actually pointing to an actual memory right?

Wrong, it does point to an actual memory whose allocation implementation is hidden from you. And this memory lies in the Read-Only sector of memory, so that it can't be changed/modified. Hence the keyword const as these literals are called constant literals.

if you try to use s to modify the string, the result is undefined.

Because, you are trying to modify memory which is marked as Read-Only.

what is the point of assigning a string to the pointer then?

Another way to achieve the same is,

char temp[260] = {0} ;
char *s ;
strcpy (temp, "this is a string");
s = temp ;

Here the memory temp is managed by you.

char *s = "this is a string" ;

Here the memory is managed by the OS.

Upvotes: 1

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

If you are assigning like this,

char *s = "this is a string";

It will stored in the read only memory. So this is the reason for the undefined behavior. In this s will pointing to the some memory in the read-only area. If you print the address like this you can get the some memory address.

 printf("%p",s);

So in this case, if you allocate a memory and the copy the value to that pointer, you can access that pointer like array.

Upvotes: 0

Mohammad
Mohammad

Reputation: 362

Look at this code:

char *s = "this is a string";
printf("%s",s);

as you can see,I used "assigning a string to the pointer".Is that clear? And know that s is pointing to an actual memory,but it is read-only.

Upvotes: 0

Gopi
Gopi

Reputation: 19874

char *s = "this is a string";

This is a string literal. So the string is stored in read-only location and that memory address is returned to s . So when you try to write to the read-only location you see undefined behavior and might see a crash.

Q1:s is not actually pointing to an actual memory right?

You are wrong s is holding the memory address where this string is stored.

Q2:what is the point of assigning a string to the pointer then?

http://en.wikipedia.org/wiki/String_literal

Upvotes: 3

Related Questions