1
#include <stdio.h>

  int main(void){
   char c[8];
   *c = "hello";
   printf("%s\n",*c);
   return 0;
   }

I am learning pointers recently. above code gives me an error - assignment makes integer from pointer without a cast [enabled by default]. I read few post on SO about this error but was not able to fix my code. i declared c as any array of 8 char, c has address of first element. so if i do *c = "hello", it will store one char in one byte and use as many consequent bytes as needed for other characters in "hello". Please someone help me identify the issue and help me fix it. mark

frank_crane
  • 177
  • 2
  • 9

2 Answers2

1

i declared c as any array of 8 char, c has address of first element. - Yes

so if i do *c = "hello", it will store one char in one byte and use as many consequent bytes as needed for other characters in "hello". - No. Value of "hello" (pointer pointing to some static string "hello") will be assigned to *c(1byte). Value of "hello" is a pointer to string, not a string itself.

You need to use strcpy to copy an array of characters to another array of characters.

const char* hellostring = "hello";
char c[8];

*c = hellostring; //Cannot assign pointer to char
c[0] = hellostring; // Same as above
strcpy(c, hellostring); // OK
whyask37
  • 123
  • 8
1
#include <stdio.h>

   int main(void){
   char c[8];//creating an array of char
   /*
    *c stores the address of index 0 i.e. c[0].  
     Now, the next statement (*c = "hello";)
     is trying to assign a string to a char.
     actually if you'll read *c as "value at c"(with index 0), 
     it will be more clearer to you.
     to store "hello" to c, simply declare the char c[8] to char *c[8]; 
     i.e. you have  to make array of pointers 
    */
   *c = "hello";
   printf("%s\n",*c);
   return 0;
 }

hope it'll help..:)

Manisha Bano
  • 1,853
  • 2
  • 22
  • 34
  • thank you. so if i say *c = "hello", then it means that i am trying to assign 5 chars to one character. right? pointers are so hard to understand. :( – frank_crane Sep 01 '14 at 18:50
  • yes... well, if you try to understand the logic, how data is stored is memory and how its fetched,, it becomes easy for you to understand it. its not that much tough.:) hey vote my ans if it seems helping you.. – Manisha Bano Sep 04 '14 at 08:17