Why does the first function return the string "Hello, World" but the second function returns nothing. I thought the return value of both of the functions would be undefined since they are returning data that is out of scope.
#include <stdio.h> // This successfully returns "Hello, World" char* function1() { char* string = "Hello, World!"; return string; } // This returns nothing char* function2() { char string[] = "Hello, World!"; return string; } int main() { char* foo1 = function1(); printf("%s\n", foo1); // Prints "Hello, World" printf("------------\n"); char* foo2 = function2(); // Prints nothing printf("%s\n", foo2); return 0; }
Difference between char s[] and char *s in C There are some differences. The s[] is an array, but *s is a pointer. For an example, if two declarations are like char s[20], and char *s respectively, then by using sizeof() we will get 20, and 4. The first one will be 20 as it is showing that there are 20 bytes of data.
char a[]="string"; // a is an array of characters. char *p="string"; // p is a string literal having static allocation. Any attempt to modify contents of p leads to Undefined Behavior since string literals are stored in read-only section of memory.
Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string.
A simple char cIn[] in the argument list will not have the size information of the array included. You need something like template<size_t N> ... (char (&cIn)[N]) , then N will match the number of elements. Alternative: use char* start, char* end to pass the array.
the second function returns nothing
The string
array in the second function:
char string[] = "Hello, World!";
has automatic storage duration. It does not exist after the control flow has returned from the function.
Whereas string
in the first function:
char* string = "Hello, World!";
points to a literal string, which has static storage duration. That implies that, the string still exists after returning back from the function. What you are returning from the function is a pointer to this literal string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With