Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between returning a char* and a char[] from a function? [duplicate]

Tags:

c

string

pointers

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; } 
like image 544
Tobs Avatar asked Sep 07 '17 07:09

Tobs


People also ask

What is the difference between char * and char []?

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.

What is the difference between char a [] string and char * p string?

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.

Can you return char [] in C?

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.

How do I return a char pointer to an array?

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.


1 Answers

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.

like image 115
ネロク・ゴ Avatar answered Sep 20 '22 14:09

ネロク・ゴ