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

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

so is char* hellostring is different from char *hellostring?
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..:)

2 Comments

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. :(
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..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.