How to return array c

How to return array c

Returning an array using C

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

How to return array c. Смотреть фото How to return array c. Смотреть картинку How to return array c. Картинка про How to return array c. Фото How to return array c

8 Answers 8

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

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:

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.

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.

How to return an array from a function in C?

Most websites say something like this:

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.

I’ve just begun with pointers and as far as I understand, a pointer variable is a variable which stores a memory address. When we dereference it using *, we get to that memory address and hold the value stored there. Also, in the case of an array, the pointer must point to the first element.

Now, if our function returns a pointer to the first element of our array as in this 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.

In computer programming, a static variable is a variable that has been allocated statically so that its lifetime or «extent» extends across the entire run of the program.

Another website says,

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope.

Someone please give me a clear and basic explanation what a static variable really is and how it is relevant in this context(returning array from function).

I’m really confused.

How to return array c. Смотреть фото How to return array c. Смотреть картинку How to return array c. Картинка про How to return array c. Фото How to return array c

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

What and how are we going to dereference it?

The pointer variable returned by the function.

Does «the function returning a pointer» mean it is returning the memory address to which the pointer points?

It’s returning a pointer variable, this variable holds the memory address of the value. Basically, «pointing to » a value is the same as «having it’s address».

What exactly is a static variable? [I surfed enough but didn’t find anything statisfying].

There’s lots of good SO answers on what a static variable is already. To summarize (only going in on the lifetime of the variable and not it’s linkage) a static variable is valid for the rest of the program once initialized, this means that it’s lifetime is not scope bound like a local variable is:

This in turn means that it’s completely safe to return a pointer (the memory address) of a local static variable since the static variable will still be accessible :

But, doing so for a local non-static variable will cause undefined behaviour as the variable pointed to (it’s memory address) is no longer valid as it has been destroyed:

Note that the above code might run and output the expected result but that is sheer luck, this is undefined behaviour and should be avoided at all costs since anything can happen at this point.

How to return array c. Смотреть фото How to return array c. Смотреть картинку How to return array c. Картинка про How to return array c. Фото How to return array c

When the program starts, the memory for a and c are allocated and remain allocated until the program exits. So there is exactly on a and on c at any given time. Each time anyone (here main) calls foo, b is allocated on the stack until that function returns.

About the Quote in front of question 3:

Returning the address of a and c is no problem, because those exist as long as the program lasts, but returning an address to b is an error because as soon as the caller gets the pointer in his hand, the pointer points to invalid memory.

You dereference a pointer by putting an asterisk in front. It doesn’t matter, that that pointer points to. It it is an array, you can increment or decrement the pointer to get to the index you’re trying to reach like in a simple addition: *(p + 4) will access the 5th element (because *(p + 0) is the first one, so *(p + 1) is the second one and so on).

Instead of writing *(p + 4) you can also write p[4].

So assuming you function looks like this:

then the return statement will return the address of the array which is the exact same thing as the address of the first element of the array.

A function, that returns a pointer is a function that returns a pointer. A pointer is a thing, which points to a point in memory. Usually that is called a memory address, but the C language doesn’t care. So, in practice, «the function returning a pointer» means it is returning the memory address to which the pointer points, yes.

Going back to front:

What exactly is a static variable?

An object with static storage duration has storage allocated for it when the program first starts up, and that storage is held until the program exits. An object has static storage duration if:

This is why you can’t do something like

because array ceases to exist once bar exits, and the pointer that gets returned is invalid.

Now, one way around this is to declare the array as static :

In this case, array doesn’t go away when the function exits, so the pointer is still valid.

Either pass a target array as an argument to the function:

or dynamically allocate an array and return the pointer to it:

The problem with this is that someone else is responsible for releasing that memory when you’re done.

Does «the function returning a pointer» mean it is returning the memory address to which the pointer points?

What and how are we going to dereference it?

So, does this mean arrays and pointers are the same thing? No. Arrays are not pointers; however, under most circumstances, an array expression (i.e., an expression of type «N-element array of T «) will be converted («decay») to a pointer expression («pointer to T «).

How to return an array from a function?

How can I return an array from a method, and how must I declare it?

5 Answers 5

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

but it would be «more C++» to use vectors:

EDIT
I’ll clarify some point. Since you mentioned C++, I’ll go with new[] and delete[] operators, but it’s the same with malloc/free.

In the first case, you’ll write something like:

A better signature would be this one:

And your client code would now be:

Since this is C++, std::vector is a widely-used solution:

which is easier and safer.

How to return array c. Смотреть фото How to return array c. Смотреть картинку How to return array c. Картинка про How to return array c. Фото How to return array c

This sounds like a simple question, but in C++ you have quite a few options. Firstly, you should prefer.

std::array<> (introduced with C++11), which always stores a number of elements specified at compile time,

. as they manage memory for you, ensuring correct behaviour and simplifying things considerably:

If you really want to use an inbuilt array (as distinct from the Standard library class called array mentioned above), one way is for the caller to reserve space and tell the function to use it:

Starting with the above, if you’re stuck using C++03 you might want to generalise it into something closer to the C++11 std::array :

Another option is to have the called function allocate memory on the heap:

To help simplify the management of heap objects, many C++ programmers use «smart pointers» that ensure deletion when the pointer(s) to the object leave their scopes. With C++11:

How to make an array return type from C function?

I have tried to return the array name as shown below. Basically I am trying to make the function test return an array that can be used in main. Could you advise me as to what I need to read into more to find out how to perform a function like this?

I receive the compiler errors:

14 Answers 14

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Functions can’t return arrays in C.

However, they can return structs. And structs can contain arrays.

You can return an array by returning a pointer (arrays decays to pointers). However, that would be bad in your case, as then you would be returning a pointer to a local variable, and that results in undefined behaviour. This is because the memory the returned pointer points to is no longer valid after the function returns, as the stack space is now reused by other functions.

What you should do is to pass the array and its size both as arguments to the function.

You also have another problem in your code, and that is you use an array of size two, but write to a third element.

How to return array c. Смотреть фото How to return array c. Смотреть картинку How to return array c. Картинка про How to return array c. Фото How to return array c

You will need to allocate memory on the heap and return a pointer. C cannot return arrays from functions.

How to return array c. Смотреть фото How to return array c. Смотреть картинку How to return array c. Картинка про How to return array c. Фото How to return array c

Unfortunately C does not support return of arbitrary arrays nor anonymous structs from functions, but there two workarounds.

The first workaround is to create a struct containing the array in it. It’s going to have the same size as the array, be allocated on the stack ensuring space locality.

The second workaround is to invent a static memory pool(e.g. array with custom malloc/free for this array only), and this will effectively allow you to dynamically allocate memory from this pool, again, effectively returning a pointer to contiguous stack space, which is by definition an array.

Then implement my_alloc, my_free that manage this specific memory pool, again ensuring that the memory created is on the stack, and the memory is already owned by your application apriori(whereas malloc might allocate memory previously not accessible by application or crash if not enough memory and didn’t check for fail return).

The third workaround is to have the function return a local variable to a callback function; this ensures that once the function finishes, you can use the result without corrupting the stack because the function using the memory will be sitting above the scope that contains the stack.

This is more efficient than a non-stacklike memory pool which needs to make decisions to avoid fragmentation, more efficient than a stacklike memory pool which just puts the result on top of the stack because it doesn’t need to copy the string, and more threadsafe because the return value of the function doesn’t risk being overwritten by another thread(unless a lock is used).

The funny thing is that all «functional programming paradigm» programs end up emphasizing that you can write C programs without any malloc by chaining callback functions, effectively allocating on the stack.

This has an interesting side effect of making linked lists no longer cache hostile(since callback linked lists allocated on the stack are all going to be near each other on the stack, which lets you do things like runtime string manipulation without any mallocs, and lets you built up unknown sized user inputs without doing any mallocs.

Function with return type array in C

I have the following function in C:

If yes, how can I return the array ( var ) in the function?

How to return array c. Смотреть фото How to return array c. Смотреть картинку How to return array c. Картинка про How to return array c. Фото How to return array c

5 Answers 5

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You can’t really return an array from a function, but a pointer:

This code below could clarify a bit how array and pointers works. The function will allocate memory for «tags» int variables, then it will initialize each element with a number and return the memory segment that points to the array. From the main function we will cycle and print the array element, then we will free the no longer needed memory.

Arrays and pointers to the base element type are (mostly) synonymous in C/C++, so you can return a pointer to the first element of an array and use that as if it was the array itself.

Also, you will have to call free() on the pointer returned by function above, when you are no longer using the array, to avoid memory leaks. malloc above allocates memory enough to hold tags number of int s, so the array is equivalent to int var;

UPDATE: removed cast for malloc ‘s return

In C, functions cannot return array types. For your purposes, you want to return a pointer to int :

You can use the subscript oprerator on a pointer expression as though it were an array, like so:

arr is a pointer expression, not an array expression, so sizeof arr will return the size of the pointer type, not the size of the block of memory that it points to (because of this, you will want to keep track of the number of elements you allocated separately).

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *