C return char array

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array’s name without an index.

If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example −

Second point to remember is that C does not advocate to return the address of a local variable to outside of the function, so you would have to define the local variable as static variable.

Now, consider the following function which will generate 10 random numbers and return them using an array and call this function as follows −

When the above code is compiled together and executed, it produces the following result −

Welcome to LinuxQuestions.org, a friendly and active Linux Community.

You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!

Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.

Are you new to LinuxQuestions.org? Visit the following links:
Site Howto | Site FAQ | Sitemap | Register Now

If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.

Having a problem logging in? Please visit this page to clear all LQ-related cookies.

Introduction to Linux — A Hands on Guide

This guide was created as an overview of the Linux Operating System, geared toward new users as an exploration tour and getting started guide, with exercises at the end of each chapter. For more advanced trainees it can be a desktop reference, and a collection of the base knowledge needed to proceed with system and network administration. This book contains many real life examples derived from the author’s experience as a Linux system and network administrator, trainer and consultant. They hope these examples will help you to get a better understanding of the Linux system and that you feel encouraged to try out things on your own.

Читайте также:  Как на айфоне менять язык на клавиатуре

I am relatively new to C and I need some help with methods dealing with arrays. Coming from Java programming, I am used to being able to say int [] method() in order to return an array. However, I have found out that with C you have to use pointers for arrays when you return them. Being a new programmer, I really do not understand this at all, even with the many forums I have looked through.

Basically, I am trying to write a method that returns a char array in C. I will provide the method (lets call it returnArray) with an array. It will create a new array from the previous array and return a pointer to it. I just need some help on how to get this started and how to read the pointer once it is sent out of the array. Any help explaining this is appreciated.

Proposed Code Format for Array Returning Function

Caller of the Function

I have not tested this yet as my C compiler is not working at the moment but I would like to figure this out

8 Answers 8

You can’t return arrays from functions in C. You also can’t (shouldn’t) do this:

returned is created with automatic storage duration and references to it will become invalid once it leaves its declaring scope, i.e., when the function returns.

You will need to dynamically allocate the memory inside of the function or fill a preallocated buffer provided by the caller.

Option 1:

dynamically allocate the memory inside of the function (caller responsible for deallocating ret )

Call it like so:

Option 2:

fill a preallocated buffer provided by the caller (caller allocates buf and passes to the function)

Читайте также:  Принципиальная схема бесперебойного блока питания

And call it like so:

C’s treatment of arrays is very different from Java’s, and you’ll have to adjust your thinking accordingly. Arrays in C are not first-class objects (that is, an array expression does not retain it’s "array-ness" in most contexts). In C, an expression of type "N-element array of T " will be implicitly converted ("decay") to an expression of type "pointer to T ", except when the array expression is an operand of the sizeof or unary & operators, or if the array expression is a string literal being used to initialize another array in a declaration.

Among other things, this means that you cannot pass an array expression to a function and have it received as an array type; the function actually receives a pointer type:

In the call to foo , the expression str is converted from type char [6] to char * , which is why the first parameter of foo is declared char *a instead of char a[6] . In sizeof str , since the array expression is an operand of the sizeof operator, it’s not converted to a pointer type, so you get the number of bytes in the array (6).

If you’re really interested, you can read Dennis Ritchie’s The Development of the C Language to understand where this treatment comes from.

The upshot is that functions cannot return array types, which is fine since array expressions cannot be the target of an assignment, either.

The safest method is for the caller to define the array, and pass its address and size to the function that’s supposed to write to it:

Читайте также:  Почему не заряжается навигатор

Another method is for the function to allocate the array dynamically and return the pointer and size:

In this case, the caller is responsible for deallocating the array with the free library function.

Note that dst in the above code is a simple pointer to char , not a pointer to an array of char . C’s pointer and array semantics are such that you can apply the subscript operator [] to either an expression of array type or pointer type; both src[i] and dst[i] will access the i ‘th element of the array (even though only src has array type).

You can declare a pointer to an N-element array of T and do something similar:

Several drawbacks with the above. First of all, older versions of C expect SOME_SIZE to be a compile-time constant, meaning that function will only ever work with one array size. Secondly, you have to dereference the pointer before applying the subscript, which clutters the code. Pointers to arrays work better when you’re dealing with multi-dimensional arrays.