4

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);
Karthikeyan.R.S
  • 3,991
  • 1
  • 19
  • 31
Karthick
  • 1,010
  • 1
  • 8
  • 24

2 Answers2

2

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");
Anto Jurković
  • 11,188
  • 2
  • 29
  • 42
  • So u mean to say that when ever we assign a string literal, it would be stored somewhere in the memory and that address would be assigned? – Karthick Apr 07 '15 at 18:06
  • Yes. Additionaly using `char *string = "abc";` you cannot change content later. See for example [C Program String Literals](http://stackoverflow.com/questions/7774770/c-program-string-literals) – Anto Jurković Apr 07 '15 at 18:40
1

*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");
Community
  • 1
  • 1
Karthikeyan.R.S
  • 3,991
  • 1
  • 19
  • 31