简体   繁体   中英

Passing Malloc char pointer to function

When I try to pass a malloc 'd char pointer from main to use in user_input to get a string in it. After the while loop is done I'm trying to print filename . filename ends up to be empty when it should contain a valid string.

void user_input(char *filename){
    char ch;

    int i = 0;

    printf("Fil att leta i: ");
    while((ch = getchar()) == '\n'){
        filename = realloc(filename, (i+1) * sizeof(char));
        filename[i] = ch;

        i++;
    }
    filename[i] = '\0';
    printf("filnamn = %s", filename);

}

int main(void){
    char *filename;

    filename = (char *)malloc(sizeof(char));
    user_input(filename);

    return 0;
}

The filename is a pointer which is passed by value. When you do this in the user_input function

filename = realloc(filename, (i+1) * sizeof(char));

the filename in the main does not change. When you print filename in the main , the pointer has been realloced, so you trigger undefined behavior.

You need to pass filename by pointer. Since it's already a pointer, you end up with a double pointer:

void user_input(char **filenamePtr)

Now you need to take a pointer in the main

user_input(&filename);

and dereference in the user_input :

*filenamePtr = realloc(*filenamePtr, i+2);

Note that sizeof(char) is always 1 , so you do not need to multiply by it. Also you add 2, not 1, to i so that you have enough space for the null terminator '\\0' character.

Change this:

while((ch = getchar()) == '\n')

into this:

while((ch = getchar()) != '\n')

you only read the \\n . You should read anything but the \\n .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM