0
votes

This is part of my main function, I'm passing the char array into the get file_file(file) function.

int main(int argc, char** argv) {
    char file[60];
    get_file(file);
    return (EXIT_SUCCESS);
}

This is the get file method that I have made. I just want it to return 'file' back to the main method to be passed into multiple other methods but I'm getting the segmentation fault straight after the scanf statement according to debugging.

    void get_file(char file) {
        printf("What file do you want?");
        scanf(" %s",file);
//do other stuff
    return file;
    }
3

3 Answers

4
votes

file is an array in main(). You have to receive it with a pointer to char variable, because an array decays into a pointer when it is sent to a function.

Use something like this,

void get_file(char* file)

Another problem in your code is the return type. If you want to return something from the function, you need to change its return type(it should not be void) and receive it in the calling function.

In your case, you do not need to return file, as the input is stored in the address sent to the function.

Be aware though, that you need to specify the size of the string to be read, else it can cause buffer overflow.

scanf(" %59s",file);
3
votes

A char array decays (implicitly converted when passed to a function) to a pointer, not a char. Define get_line like

void get_file(char* file) {
    ...
}

instead.

One char can only hold one character, so a buffer overflow would occur. Also, sizeof(char*) usually is greater than sizeof(char) == 1, so the address is truncated and probably turns into an invalid address.
The compiler actually should've issued some warning, though.

1
votes

You are missing the * in the get_file declaration. You want to pass the pointer to the array, not the value for the positon itself. That way, you should type

 void get_file(char* file)