Karthick
Karthick

Reputation: 1000

How to store a string into a char pointer?

I have a confusion with the following program

#include<stdio.h>
void main()
{
char *string;
string = (char *)malloc(5);
string = "abc";  // <<<<<<<<<< why *string="abc" is not working. How string = "abc" is working?
printf("%s", string);
}

But the same program with integer is working

char *i;
 i=(int *)malloc(sizeof(int));
*i=4;  <<<<<<<< this is working fine
printf("%d",*i);

Upvotes: 4

Views: 27521

Answers (2)

Anto Jurković
Anto Jurković

Reputation: 11258

Why *string = "abc" is not working?

string is defined as pointer to char. *string is a char. "abc" is a string literal. You are actually assigning address of string literal to char and compiler should issue warning like:

warning: assignment makes integer from pointer without a cast

For example, *string = 'a'; will work because just one char is assigned.

How string = "abc" is working?

Because address of string literal "abc" is assigned to string which is a pointer to char.

And BTW, doing that you lost previously allocated memory by malloc() and produced memory leak.

How to store a string into a char pointer? You can use just:

strcpy(string, "abc");

Upvotes: 2

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

*string is point out the single character.Here "abc" is string literal. It is not a character.

*string='a'; // It will work.

Don't cast the result of malloc and its family.

You can use the strcpy function to do this.

strcpy(string,"abc");

Upvotes: 1

Related Questions