androidFan
androidFan

Reputation: 621

Can a string pointer in C be directly assigned a string literal?

The following program works fine, and I'm surprised why :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void xyz(char **value)
{
        // *value = strdup("abc");
        *value = "abc"; // <-- ??????????
}

int main(void)
{
        char *s1;

        xyz(&s1);

        printf("s1 : %s \n", s1);
}

Output :

s1 : abc

My understanding was that I have to use strdup() function to allocate memory for a string in C for which I have not allocated memory. But in this case the program seems to be working fine by just assigning string value using " ", can anyone please explain ?

Upvotes: 5

Views: 1413

Answers (3)

parth_07
parth_07

Reputation: 1408

Your program works fine because string literal "abc" are character arrays , and what actually happens while assigning a string literal to a pointer is , the compiler first creates a character array and then return the address of the first element of the array just like when we call the name of any other array. so in your program you have passed address of a char pointer to the function xyz and

*value = "abc";

for this statement , compiler first creates a character array in the memory and then returns its address which in turn gets stored in the char pointer.It is worth knowing that the compiler creates the char array in read only memory.Thus , the address returned refers to a const char array.Any attempt to modify its value will return it compile-time error.

Upvotes: 4

Jeff
Jeff

Reputation: 11

You can define a string in C with char *str = "some string";, str is a pointer which points to the location of the first letter in a string.

Upvotes: 1

String literals don't exist in the ether. They reside in your programs memory and have an address.

Consequently you can assign that address to pointers. The behavior of your program is well defined, and nothing bad will happen, so long as you don't attempt to modify a literal through a pointer.

For that reason, it's best to make the compiler work for you by being const correct. Prefer to mark the pointee type as const whenever possible, and your compiler will object to modification attempts.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void xyz(char const **value)
{
        *value = "abc";
}

int main(void)
{
        char const *s1;

        xyz(&s1);

        printf("s1 : %s \n", s1);
        s1[0] = 'a'; << Error on this line
}

Upvotes: 7

Related Questions