-1

hello i have my funcion like:

void enterString(char *string) {

    string = (char*)malloc(15);

    printf("Enter string: ");
    scanf("%s",string); //don't care about length of string now
}

int main() {
   char *my_string = NULL;
   enterString(my_string);

   printf("My string: %s\n",my_string); /* it's null but i want it to 
                                          show string i typed from 
                                           enterString */

   return 0;
}

I want to string from function show on string in main ... I don't know if you'll understand me. Thank you :)

miskohut
  • 957
  • 1
  • 14
  • 34

1 Answers1

3

You are passing string by value. You neet to pass it by address :

void enterString(char **string) {

    *string = (char*)malloc(15);

    printf("Enter string: ");
    scanf("%s",*string); //don't care about length of string now //you should!
}

int main() {
   char *my_string = NULL;
   enterString(&my_string);

   printf("My string: %s\n",my_string);

   free(my_string);

   return 0;
}
Quentin
  • 62,093
  • 7
  • 131
  • 191
  • 2
    Care to argument the downvote ?... – Quentin Jun 02 '14 at 12:37
  • Why would I have to argument the downvote? – this Jun 02 '14 at 12:38
  • 3
    So I can know what is wrong with my answer and improve it for everyone's gain. That's what this site is all about, right ? – Quentin Jun 02 '14 at 12:39
  • 1
    I was asking that in hope that the person having cast the downvote would see it and answer accordingly. Don't take it personally if it wasn't you :p – Quentin Jun 02 '14 at 12:42
  • On a second though; `scanf("%s",*string);` no! – this Jun 02 '14 at 12:43
  • 2
    You may want to double-check that comment, string is a char** ;) – Quentin Jun 02 '14 at 12:47
  • My comment is perfectly fine; you missed the point. What happens when the user enters >15 characters? – this Jun 02 '14 at 13:13
  • Tears and damnation. But OP explicitly dismissed the case (that's his comment up there). – Quentin Jun 02 '14 at 13:15
  • If you can't take the criticism don't ask for it. – this Jun 02 '14 at 13:25
  • Now I really don't see why you're upset... You're perfectly right about buffer overflowing, but OP stated that he didn't care for now, so I didn't bother and focused on his actual question. Feel free to comment on the Question where the problem is though :) – Quentin Jun 02 '14 at 13:37
  • *Now I really don't see why you're upset...* ? I'm not. *Feel free to comment on the Question where the problem is though :)* I already did that. – this Jun 02 '14 at 13:52
  • All good then. Imperative comment added to OP's quoted code for completeness. – Quentin Jun 02 '14 at 13:56