If this is possible:
#include <stdio.h>
#include <process.h>
#define SIZE 5
void PassingArray(int arr[])
{
int i=0;
for(i=0 ; i<SIZE ; i++)
{
printf("%d, ", arr[i]);
}
printf("\n");
}
main()
{
int myIntArray[5] = {1, 2, 3, 4, 5};
PassingArray(myIntArray);
system("PAUSE");
}
Then why the following is illegal?
#include <stdio.h>
#include <process.h>
#define SIZE 5
int ReturningArray()[]
{
int myIntArray[5] = {1, 2, 3, 4, 5};
return myIntArray;
}
main()
{
int myArray[] = ReturningArray();
system("PAUSE");
}
You're not returning an int, but you're returning the array. This is the same value as &myIntArray[0]. int ReturningArray()[] is not a valid function prototype.
There's multiple reasons why this doesn't work.
The first is simply that it's prohibited by the language - the return type of a function shall not be an array (it also can't be a function).
The second is that even if you were allowed to declare ReturningArray as you do, you could never write a valid return statement in that function - an expression with array type that is not the subject of the unary & or sizeof operators evaluates to a pointer to the first element of the array, which no longer has array type. So you can't actually make return see an array.
Thirdly, even if we somehow had a function returning an array type, you couldn't use that return value as the initialiser of an array variable - the return value would again evaluate to a pointer to the first element of the array: in this case a pointer to int, and a pointer to int isn't a suitable initialiser for an array of int.
There are several problems with this code.
You are placing the brackets at the wrong place. Instead of
int ReturningArray()[]
it should be
int* ReturningArray()
You are returning a local variable. Local variables only exist during the execution of the function and will be removed afterwards.
In order to make this work you will have to malloc the int array and return the pointer to the array:
#include <stdio.h>
#include <malloc.h>
#define SIZE 5
int* ReturningArray()
{
int *myIntArray = (int *)malloc(SIZE * sizeof(int));
myIntArray[0] = 1;
myIntArray[1] = 2;
myIntArray[2] = 3;
myIntArray[3] = 4;
myIntArray[4] = 5;
return myIntArray;
}
int main(void)
{
int i;
int* myArray = ReturningArray();
for(i=0;i<SIZE;i++) {
printf("%d\n", myArray[i]);
}
free(myArray); // free the memory again
system("PAUSE");
return 0;
}
PassingArray is legal, but it does not pass an array. It passes a pointer to the first element of an array. void PassingArray(int arr[]) is a confusing synonym for void PassingArray(int *arr). You can't pass an array by value in C.
ReturningArray is not allowed, you can't return an array by value in C either. The usual workaround is to return a struct containing an array:
typedef struct ReturnArray {
int contents[5];
} ReturnArray;
ReturnArray ReturningArray()
{
ReturnArray x = {{1, 2, 3, 4, 5}};
return x;
}
Arrays are second-class citizens in C, the fact that they can't be passed or returned by value is historically related to the fact that they can't be copied by assignment. And as far as I know, the reason for that is buried in the early development of C, long before it was standardized, when it wasn't quite decided how arrays were going to work.
You can't return array from a function, but It is possible that you can declare a function returning a (reference in C++) or pointer to array as follows:
int myIntArray[] = {1, 2, 3, 4, 5};
int (*ReturningArray())[sizeof(myIntArray)/sizeof(int)] {
return &myIntArray;
}
Related
i have my length function to calculate the length of array, but it is giving two excess garbage numbers(negative). It must return 6 but it returns 8 due to garbage values.
#include<stdio.h>
int length(int *arr) {
int _length = 0;
while (*arr) {
_length++;
arr++;
}
return _length;
}
int main() {
int arr[] = {2, 1, 3, 4, 5, 6};
printf("%d\n", length(arr));
return 0;
}
You need some manner of termination condition. while (*arr) assumes that the array ends with zero which isn't the case, so you simply can't have a loop like that.
The size of this array is known at compile time so there's no need to calculate anything in run-time.
(sizeof arr / sizeof *arr) gives you the number of items in the array, as long as you place that code in the same scope as the array declaration.
Also, using that sizeof trick (which is an idiomatic way of determining the size) inside a function-like macro is a common solution:
#include <stdio.h>
#define length(arr) (sizeof(arr)/sizeof(*arr))
int main() {
int arr[] = {2, 1, 3, 4, 5, 6};
printf("%zu\n", length(arr));
return 0;
}
I'm learning C, and tried writing a function that, given an array of integer, returns the length of the array. Here is my code:
#include <stdio.h>
int length_of_array(int array[])
{
int length = 0;
int i = 0;
while (array[i] != '\0') {
length += 1;
i += 1;
}
return length;
}
int main()
{
int test_array[] = {1, 2, 3, 4, 5};
printf("%d\n", length_of_array(test_array));
return 0;
}
However, when I compile this code and run it, I says that the length of the array passed in is 14. Does anyone know what could be the problem here?
Strings in C are NUL-terminated. Arrays are not (unless you explicitly do it yourself). The size of array is just the size of array: if allocated as a constant, you can find out the size with sizeof operator. If all you have is a plain pointer, you need to remember the size - there is no way in C to get it once you forget it.
#include <stdio.h>
int main() {
int test_array[] = {1, 2, 3, 4, 5};
int *test_ptr = test_array;
printf("%lu\n", sizeof(test_array) / sizeof(*test_array)); // correct
printf("%lu\n", sizeof(test_ptr) / sizeof(*test_ptr)); // incorrect
return 0;
}
I'm working in C, and am attempting to replicate the length member function that other languages (ie: C++) use to determine the length of an array or possibly vector of data. Is this something I can accomplish in C, or do I have to fall back onto examples like this:
int arraySize = sizeof(array) / sizeof(array[0]);
In general, in C, you use arrays as they are: a contiguous set of multiple pieces of data of the same type. You are generally expected to keep track of array sizes, along with the size of individual members, yourself.
In C++, for example, you have access to the Vector class, which encapsulates and handles all this record keeping for you.
In C, you would be expected to know exactly how big the array is. This is especially important in the case of pointer decay. Your initial example...
int arrayOfInts[6] = {1, 2, 3, 4, 5, 6};
int sizeOfArray = sizeof(arrayOfInts) / sizeof(int); // Success; Returns "6"
This works in this case, but it will fail if you were to pass the array to a function expecting an array of integers (as a pointer) as a function argument.
#include <stdio.h>
int getArraySize(int* arr);
int main(void) {
int arrayOfInts[6] = {1, 2, 3, 4, 5, 6};
int sizeOfArray = getArraySize(arrayOfInts);
return 0;
}
int getArraySize(int* arr) {
int ret;
ret = sizeof(arr) / sizeof(int); // FAILS, returns the size of a pointer-to-int, not the size of the array
return ret;
}
There are two ways to handle this: static definitions, or careful dynamic memory management.
// CASE 1: Trivial case, all arrays are of a static fixed size
#include <stdio.h>
#define ARR_SIZE (6)
int getArraySize(int* arr);
int main(void) {
int arrayOfInts[ARR_SIZE] = {1, 2, 3, 4, 5, 6};
int sizeOfArray = getArraySize(arrayOfInts);
return 0;
}
int getArraySize(int* arr) {
return ret ARR_SIZE;
}
// CASE 2: Managing sizes with dynamic allocation
#include <stdio.h>
#define ARR_SIZE (6)
int main(void) {
int sizeOfArray = ARR_SIZE;
int* arrayOfInts = malloc(sizeOfArray*sizeof(int));
if (arrayOfInts != NULL) {
// Success; initialize
int i;
for (i=0; i<sizeOfArray; i++) {
arrayOfInts[i] = i;
}
return 0;
} else {
// Failed; abort
sizeOfArray = 0;
return (-1);
}
}
I have tried this but it won't work:
#include <stdio.h>
int * retArr()
{
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
return a;
}
int main()
{
int a[3][3] = retArr();
return 0;
}
I get these errors:
Error 3 error C2075: 'a' : array initialization needs curly braces
4 IntelliSense: return value type does not match the function type
What am I doing wrong?
A struct is one approach:
struct t_thing { int a[3][3]; };
then just return the struct by value.
Full example:
struct t_thing {
int a[3][3];
};
struct t_thing retArr() {
struct t_thing thing = {
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}
};
return thing;
}
int main(int argc, const char* argv[]) {
struct t_thing thing = retArr();
...
return 0;
}
The typical problem you face is that int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; in your example refers to memory which is reclaimed after the function returns. That means it is not safe for your caller to read (Undefined Behaviour).
Other approaches involve passing the array (which the caller owns) as a parameter to the function, or creating a new allocation (e.g. using malloc). The struct is nice because it can eliminate many pitfalls, but it's not ideal for every scenario. You would avoid using a struct by value when the size of the struct is not constant or very large.
We can solve it by using Heap memory / memory allocating using stdlib :
Allocating memory using stdlib can be done by malloc and calloc.
creating array:
int ** arr=( int * * ) malloc ( sizeof ( int * ) * 5 );
is for allocating 5 rows.
arr[i]=(int *)malloc(sizeof(int)*5);
is for allocating 5 columns in each "i" row.
Thus we created arr [ 5 ] [ 5 ].
returning array:
return arr;
We just need to send that pointer which is responsible for accessing that array like above.
#include<stdio.h>
#include<stdlib.h>
int **return_arr()
{
int **arr=(int **)malloc(sizeof(int *)*5);
int i,j;
for(i=0;i<5;i++)//checking purpose
{
arr[i]=(int *)malloc(sizeof(int)*5);
for(j=0;j<5;j++)
{
arr[i][j]=i*10+j;
}
}
return arr;
}
int main()
{
int **now;
now=return_arr();
int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
printf("%d ",now[i][j]);
}
printf("\n");
}
return 0;
}
Several issues:
First of all, you cannot initialize an array from a function call; the language definition simply doesn't allow for it. An array of char may be initialized with a string literal, such as
char foo[] = "This is a test";
an array of wchar_t, char16_t, or char32_t may be initialized with a wide string literal, but otherwise the initializer must be a brace-enclosed list of values.
Secondly, you have a type mismatch; except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted to an expression of type "pointer to T", and the value of the expression will be the address of the first element;
In the function retArr, the type of a in the expression is "3-element array of 3-element array of int"; by the rule above, this will be converted to an expression of type "pointer to 3-element array of int", or int (*)[3]:
int (*retArr())[3]
{
int a[3][3] = ...;
return a;
}
but as Brendan points out, once retArr exits a no longer exists; the pointer value that is returned winds up being invalid.
#include <stdio.h>
int** retArr()
{
static int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
return a;
}
int main()
{
int** a = retArr();
return 0;
}
You could also specify the returned variable as static. You also must declare the variable a in main as just int** (and not specify the dimensions).
In the example given by the OP, it is the easiest to put the array on the stack. I didn't test this but it would be like this.
#include stdio.h
void retArr(a[][3]) {
a[0][0] = 1; a[0][1] = 2; a[0][2] = 3;
a[1][0] = 4; a[1][1] = 5; a[1][2] = 6;
a[2][0] = 7; a[2][1] = 8; a[2][2] = 9;
}
main() {
int a[3][3];
retArr(a);
}
Yeah, this doesn't "return" the array with the return function, but I would suppose that wasn't the intent of the question. The array, a[][], does get loaded, and the loaded a[][] is available in main after retArr() is called, nothing is overwritten.
For this:
int * retArr() {
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
return a;
}
The array has local scope and is destroyed as soon as you exit the function. This means that return a; actually returns a dangling pointer.
To fix this, put the array in global scope, or use malloc() and copy the array into the allocated space.
Needs to return int**, not int.
I have the following function in C:
int[] function(int a){
int * var = (int*)malloc(sizeof(int)*tags);
....
}
*var is it a pointer to an array var?
If yes, how can I return the array (var) in the function?
You can't really return an array from a function, but a pointer:
int * function(int a){
int * var = malloc(sizeof(int)*tags);
//....
return var;
}
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.
#include <stdio.h>
#include <stdlib.h>
int *function(unsigned int tags) {
int i;
int *var = malloc(sizeof(int)*tags);
for (i=0; i < tags; i++) {
var[i] = i;
}
return var;
}
int main() {
int *x;
int i;
x = function(10);
for (i=0; i < 10; i++) {
printf("TEST: %i\n", x[i]);
}
free(x); x=NULL;
return 0;
}
How about:
int* function(int tags){
int * var = malloc(sizeof(int)*tags);
//....
return var;
}
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.
Note, your code has an input parameter a, but using tags to allocate the memory for the array. I assumed in the above code that you wanted to use the input parameter for that purpose
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 ints, so the array is equivalent to int var[tags];
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:
int *function(int a)
{
int *var = malloc(sizeof *var * tags); // where is tags defined?
// are you sure you don't mean a here?
...
return var;
}
This will allocate a block of memory large enough to hold tags integer values and assign the address of the first element of that block to var. Note that var is a pointer to int, not a pointer to an array of int. That pointer is what gets returned from the function.
You can use the subscript oprerator on a pointer expression as though it were an array, like so:
int a = ...;
int *arr = function(a);
...
arr[0] = 0;
arr[1] = 1;
...
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).
In C an array is basically the same type as a pointer to an element of the array.
So char[] is basically char*
Don't forget to keep track of the size of the array, also I noticed that tags seems to be a global variable, most of the time it's a good idea to avoid global variables
Here is some example code:
#include <stdio.h>
#include <stdlib.h>
int* foo(size_t arrSize){
int* arr = (int*) malloc(sizeof(int)*arrSize);
return arr;
}
int main (int argc, char** argv){
printf("Printing array:\n");
int* arr = foo(42);
for(int i=0; i <42; i++){
arr[i]=i;
}
for (int i=0; i < 42; i++){
printf("Element: %d: %d\n", i, arr[i]);
}
free(arr);
return 0;
}