-1

I'm having problems in C with returning a string from this function:

char setup(){

    puts("Please select a size for the string");
    scanf("%d", &size);
    getchar();

    char sequence[size];

    printf("Please write any sequence of %d numbers\n", size);
    fgets(sequence, size+1, stdin);

return *sequence;
}

Size is set as a global variable. And the main:

int main(){

    int program=0;
    char sequence_alt[size];

    puts("Please select the number of the program to test:");
    scanf("%d", &program);
    getchar();

    switch(program){
    case 1:
        sequence_alt[size]=setup();
        break;

The switch goes on, but nothing else is added on this case. Instead of getting the full string, like 12345 if i choose size 5, i get only the first character. I've searched for a lot of guides but i still can't understand if the problem is actually in my function, or my main when i print the value of the sequence. Any tip and help would be awesome and i've be forever thankful. Sorry if the code is too rudimentary, but im still taking my first baby steps in learning C.

Thanks!

2 Answers2

1

Your function must return a char * (not a single char)

char setup(){
    ...
    return *sequence;
}

should be

char *setup(void){
    ...
    return sequence;
}

char sequence[size];

sequence is a local array, his lifetime ends when the function ends, use dynamic memory:

char *sequence = malloc(size);

Using size+1 in fgets you can write outside the bounds of the array, change

fgets(sequence, size+1, stdin);

to

fgets(sequence, size, stdin);
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • Thanks, it worked perfectly! I had no idea char in a function only returns a single char and not the full string. Always learning! About the size+1, if i dont add that, and i have a size 5 for example, the 5th position will be replaced by the null character, so ill only get space for 4 chars. I think its a setback of fgets. – Márcio Coelho Oct 15 '15 at 23:06
  • You are welcome, if you need 5 characters then you need to reserve space for 6 (one more for the trailing `\0`) – David Ranieri Oct 15 '15 at 23:11
0

Like the above answer explained, your function should return char* to get a string (char pointer) back and you should also know whatever you create in a function block disappears when you return from the function. so sequence can only return the first character even if it was char* since there was no memory allocated for a string of that size. The following will work fine

char* setup(){

    puts("Please select a size for the string");
    scanf("%d", &size);
    getchar();

    char *sequence = malloc(sizeof(int) * size);

    printf("Please write any sequence of %d numbers\n", size);
    fgets(sequence, size+1, stdin);

    return sequence;
}
Lukas
  • 3,423
  • 2
  • 14
  • 26