-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 :)

0

1 Answer 1

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

12 Comments

Care to argument the downvote ?...
Why would I have to argument the downvote?
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 ?
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
You may want to double-check that comment, string is a char** ;)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.