-1

How can i return a string for work with? I dont know why this function arent working.

#include <stdio.h>

char* test(){
   char A[100];
   scanf("%s", A);
   printf("A = %s \n", A);
   return(A);
}

main(){
    char* B;
    B = test();
    printf("B = %s \n", B);  // why this return (null)?
}
juanjpnv
  • 11
  • 5

1 Answers1

4

This is undefined behavior. It might return the "correct" value; it might as well do something completely different, crash the program, or worse. The reason why it is undefined behavior is as follows:

char* test(){
    char A[100];
    scanf("%s", A);
    printf("A = %s \n", A);
    return(A);
}

Here you declare an array of 100 char on the stack. Later you return the address to that memory. However, it was on the stack, so that memory is invalid now. You then assign this invalid memory pointer to B:

char* B;
B = test();

So on this line:

printf("B = %s \n", B);  // why this return (null)?

You have undefined behavior.

Instead, try this:

char* test() {
    char* A = malloc(100);
    scanf("%s", A);
    printf("A = %s \n", A);
    return A;
}

In this function, the memory is allocated on the heap instead. This way, the pointer you return is valid (also note that you don't need any parentheses around the A in return A;). Don't forget to free the memory again, though. You do it by calling this at the end of your program:

free(B);

Note that for your code, your compiler will likely emit a warning. It might say something like:

returning address of local variable or temporary: A

Those warnings can help you find potential problems and debug your code. When a program isn't working, try resolving all the warning first.

Blaze
  • 16,736
  • 2
  • 25
  • 44