I was searching for an efficient way to create a 2D array and return it, usually I make an array of pointers, allocate memory for each pointer, and return an **ptr. I was looking for another way to do it because then I have to free every single memory allocated.
I was reading online that you can allocate a 2D array like this: int (*arr)[n] = malloc( sizeof *arr * i );
In which ptr is a pointer, pointing to the adress of arr[n].
When I try to return arr, from the following function: int *array_of_smallest(int count);
I get: warning: assignment to ‘int *’ from incompatible pointer type ‘int (*)[n]’ [-Wincompatible-pointer-types]
If I initialise another pointer and point it to array, then return it, I'm only returning a 1D array.
I think I'm mixing diferent concepts and confusing myself.
With an array of pointers I don't have a problem, but I wanted a simplier way to create a 2D array, also easier to free, but I'm not being able to return that array from my function.
You declared a pointer of the variable modified type type int ( * )[n].
int (*arr)[n] = malloc( sizeof *arr * i );
That is the variable n used in the declarator is not an integer constant expression.
In this case the function should have the return type void *. And it can be declared like
void * array_of_smallest(int count)
{
int (*arr)[n] = malloc( sizeof *arr * i );
//...
return arr;
}
In the caller you will write
int ( *arr )[n] = array_of_smallest( count );
In this declaration the value of n must be the same as used within the function.
If to use an integer constant expression like
int (*arr)[2] = malloc( sizeof *arr * 2 );
then the function declaration will look like
int ( * array_of_smallest(int count) )[2];
Or you can introduce a typedef name before the function declaration like
typedef int Array[2];
and in this case the function will look like
Array * array_of_smallest(int count);
The fundamental issue with returning the array is that it is not possible to declare Variably-Modified Type (like a pointer to VLA) at the file scope.
The reason of the problem can be explained as follow. Your code behaves more or less like this:
typedef int T[n];
T* array_of_smallest(int count) { ... }
Unfortunately, defining such a type T is not possible because of two reasons:
n is usually not visible at file scope, except if it was a global variable
evaluation of n would require code execution at file scope which is forbidden
Workarounds
Return void* as described in other answer.
Pass a pointer to VLA in "by-reference" style, as a pointer to a pointer to array
void array_of_smallest(int count, int (**p)[n]) {
...
*p = arr;
}
Return a pointer to incomplete array type of int[]. It is not possible to return incomplete types but it is possible to return a pointer to incomplete types:
int (*array_of_smallest(int count))[] { ... }
or a bit cleaner with a help of typeof extension (feature in C23)
typeof(int[]) *array_of_smallest(int count) { ... }
And use it as in the void* case:
int ( *arr )[n] = array_of_smallest( count );
This solution provides type-checking for the element type, however it works only for 2-dimensional arrays.
Wrap the pointer into a structure and use a macro to reconstruct its type on the client side:
typedef struct {
int rows, cols;
void* data;
} Arr2D;
Arr2D array_of_smallest(int count) {
...
return (Arr2D) { .rows = i, .cols = n, .data = arr };
}
#define ARR2D_DEF_VIEW(view, arr2d) int (*view)[(arr2d).cols] = (arr2d).data
... usage ...
Arr2D arr = array_of_smallest(42);
ARR2D_DEF_VIEW(view, arr);
... do stuff with view[i][j]
}
Alternatively, use typeof extension to infer the type of VLA view rather than declare it in a macro:
#define ARR2D_VIEW_TYPE(arr2d) typeof(int(*)[(arr2d).cols])
...
Arr2D arr = array_of_smallest(42);
ARR2D_VIEW_TYPE(arr) view = arr.data;
Related
I'm trying to make 2D array struct in C like this in main function.
function_1(struct example** ex){}
void main(){
struct example ex[num_1][num_2];
function(ex);
}
But gcc keep telling me that type of ex and struct example** ex is different.
How can I solve this error?
I edited my original answer:
You could instead write
function_1(struct example (*pex) [num_1][num_2]){}
void main(){
struct example ex[num_1][num_2];
function(& ex);
}
at least if you know num_1 and num_2 at compile time.
A 2D array expression doesn’t decay to a pointer to pointer, it decays to a pointer to an array.
Unless it is the operand of the sizeof, _Alignof, or unary & operators, or is a string literal used initialize a character array in a declaration, an expression of type "N-element array of T" will be converted, or "decay", to an expression of type "pointer to T" and the value of the expression will be the address of the first element of the array.
In the call to function, the expression ex decays from type "num_1-element array of num_2-element array of struct example" to "pointer to num_2-element array of struct example", so your function prototype needs to be
void function( struct example (*ex)[num_2] )
{
...
ex[i][j] = some_value();
...
}
In the context of a function parameter declaration, T a[N] and T a[] are "adjusted" to T *a, so you could also write that prototype as
void function( struct example ex[][num_2] )
{
...
ex[i][j] = some_value();
...
}
There are a couple of problems with this - function doesn’t know how many rows are in the array, so you would need to pass that as a separate parameter:
void function( struct example (*ex)[num_2], size_t rows )
{
...
}
Also the function can only accept arrays with num_2 columns - it cannot work on any arbitrarily-sized 2D array.
If your function needs to handle arbitrarily-sized arrays and you have a compiler that supports variable-length arrays, you can do something like this:
void function( size_t rows, size_t cols, struct example ex[rows][cols] )
{
...
}
and call it from main as
function( num_1, num_2, ex );
If your compiler doesn’t support VLAs, you’ll have to get creative. One trick is to pass a pointer to the first element and treat it as a 1D array in the function:
void function( struct example *ex, size_t rows, size_t cols )
{
...
ex[i * rows + j] = some_value();
...
}
and call it as
function( &ex[0][0], num_1, num_2 );
Note that this trick only works for 2D arrays defined as
T a[M][N];
or arrays dynamically allocated as
T (*p)[N] = malloc( sizeof *p, M );
It won’t work for 2D arrays allocated as
T **p = malloc( sizeof *p * M );
for ( size_t i = 0; i < N; i++ )
p[i] = malloc( sizeof *p[i], N );
but in that case, your function prototype would be
void function( T **p, size_t rows, size_t cols )
{
...
}
As a final note, main returns int, not void. Older compilers won’t complain, but the behavior is undefined and could cause problems at runtime.
Consider the given 2d array allocation:
int (*some)[10] = malloc(sizeof(int[10][10]));
This allocates a 10 x 10 2d array. Apparently its type is int (*)[10]. I want to write a function initialize() that will allocate it, initialize it and then return a pointer to the array, so that the construction some[i][j] would be usable in other functions which can pass a pointer to the array it onto each other.
What should the prototype, specifically the return type of initialize() be?
int (*initialize(void))[10] { ... }
initialize is a function, which takes no parameters and returns a pointer to an array of 10 int.
You should use a typedef for that.
allocates the table of nrow pointers to (allocated) int array of size elements
void *allocate_rows(int *(*ptr)[size], size_t nrows)
{
int (*tmpptr)[size] = *ptr;
*ptr = malloc(nrows * sizeof(*ptr));
if(*ptr)
{
while(nrows--)
{
tmpptr = malloc(sizeof(*tmpptr));
if(!tmpptr)
{
/* malloc failed do something */
}
else
{
tmpptr++;
}
}
return *ptr;
}
In
int (*some)[10] = malloc(sizeof *some);, some is a "pointer to an array of 10 int`.
If you want other to be a function returning a pointer to an array of of 10 int, you can start with int (*some)[10]; and replace some with what a call to a such function would look like to get your declaration.
int (*some)[10]; => int (*other(argument1,argument2))[10];
That's how it worked in pre-standardized C. Since standardized C has prototypes, you'd also replace the argument identifier list with a parameter type list, e.g.:
int (*other(int argument1, double argument2))[10];
The cdecl program or the cdecl website can help you verify the result:
$ echo 'explain int (*other(int,double))[10]'|cdecl
declare other as function (int, double) returning pointer to array 10 of int
Most people find typedefs more readable:
typedef int (*pointer_to_an_array_of_10_int)[10];
pointer_to_an_array_of_10_int other(int, double);
//to verify it's a compatible declaration
int (*other(int , double ))[10];
I've a little question.
I'm trying to define an array of function pointers dynamically with calloc.
But I don't know how to write the syntax.
Thanks a lot.
The type of a function pointer is just like the function declaration, but with "(*)" in place of the function name. So a pointer to:
int foo( int )
would be:
int (*)( int )
In order to name an instance of this type, put the name inside (*), after the star, so:
int (*foo_ptr)( int )
declares a variable called foo_ptr that points to a function of this type.
Arrays follow the normal C syntax of putting the brackets near the variable's identifier, so:
int (*foo_ptr_array[2])( int )
declares a variable called foo_ptr_array which is an array of 2 function pointers.
The syntax can get pretty messy, so it's often easier to make a typedef to the function pointer and then declare an array of those instead:
typedef int (*foo_ptr_t)( int );
foo_ptr_t foo_ptr_array[2];
In either sample you can do things like:
int f1( int );
int f2( int );
foo_ptr_array[0] = f1;
foo_ptr_array[1] = f2;
foo_ptr_array[0]( 1 );
Finally, you can dynamically allocate an array with either of:
int (**a1)( int ) = calloc( 2, sizeof( int (*)( int ) ) );
foo_ptr_t * a2 = calloc( 2, sizeof( foo_ptr_t ) );
Notice the extra * in the first line to declare a1 as a pointer to the function pointer.
I put a small example here that may help you
typedef void (*fp)(int); //Declares a type of a void function that accepts an int
void test(int i)
{
printf("%d", i);
}
int _tmain(int argc, _TCHAR* argv[])
{
fp function_array[10]; //declares the array
function_array[0] = test; //assings a function that implements that signature in the first position
function_array[0](10); //call the cuntion passing 10
}
You'd declare an array of function pointers as
T (*afp[N])();
for some type T. Since you're dynamically allocating the array, you'd do something like
T (**pfp)() = calloc(num_elements, sizeof *pfp);
or
T (**pfp)() = malloc(num_elements * sizeof *pfp);
You'd then call each function as
T x = (*pfp[i])();
or
T x = pfp[i](); // pfp[i] is implicitly dereferenced
If you want to be unorthodox, you can declare a pointer to an array of pointers to functions, and then allocate that as follows:
T (*(*pafp)[N])() = malloc(sizeof *pafp);
although you would have to deference the array pointer when making the call:
x = (*(*pafp)[i])();
typedef R (*fptr)(A1, A2... An);
where R is the return type, A1, A2... An are the argument types.
fptr* arr = calloc(num_of_elements,sizeof(fptr));
Assuming all your functions are of type void ()(void), something like this
typedef void (*fxptr)(void);
fxptr *ptr; // pointer to function pointer
ptr = malloc(100 * sizeof *ptr);
if (ptr) {
ptr[0] = fx0;
ptr[1] = fx1;
/* ... */
ptr[99] = fx100;
/* use "dynamic array" of function pointers */
free(ptr);
}
I have a function which accepts int* pInput[] as an argument.
void Process(int* pInput[], unsigned int num);
I have to call this function via 2 methods as
main()
{
int *pIn[2];
int input[2][100] = {0};
pIn[0] = ( int* )malloc( 100 * sizeof( int) );
pIn[1] = ( int* )malloc( 100 * sizeof( int) );
Process( pIn, 2 );
Process( ( int** )input, 2 );
}
Then how can i access each value of pInput inside function 'Process'?I cannot access it directly as pIn[0][0].
how can i access each value of pInput inside function 'Process'?I cannot access it directly as pIn[0][0].
No! You can access it exactly that way: pInput[0][0] if the input you pass is pIn. This is because pIn is an array of int*s I.e. it's of type int *[n] each of its element pointing to an array of ints. It would decay into int**.
However, if you want to pass input, a 2D array of ints, you've to do more since a 2D array doesn't decay into a double pointer, T** but into a pointer to an array, T (*) [n]. This is because array decay is not recursive, it happens only to the first level. Alternatively, you can do this (Live example)
pIn[0] = input[0];
pIn[1] = input[1];
and now pass pIn to Process. Here pIn is a surrogate for input and it needs to have as many elements as input, which is not a very elegant solution. A better way to pass input, when you know the dimensions during compile-time is
void Process(int (*pInput)[100], size_t rows) { }
void Process(int input [2][100], size_t rows) { }
/* These two are the same; the compiler never sees the `2`. input's type is int(*)[100] */
Read on array decay to understand the situation better.
Aside
Do I cast the result of malloc? No, you do not need to cast the return value of malloc in C.
What should main() return in C and C++? The return type of main should be int.
Related
C-FAQ: My compiler complained when I passed a two-dimensional array to a function expecting a pointer to a pointer.
What is array decaying?
Why can we omit the first dimension of a multidimensional array when we are passing it to a function
In your process() function you just need to access it normally like any 2d array as below. Calling both ways are same.
void Process( int * pInput[], unsigned int num)
{
printf(" %d", pInput[0][0]); //printing value of pInput[0]
printf(" %d", pInput[1][0]); //printing value of pInput[1]
pInput[0][0] = 8054; // changing its value.
pInput[1][0] = 8055; // changing its value.
}
int main()
{
int *pIn[2];
int input[2][100] = {0};
pIn[0] = ( int* )malloc( 100 * sizeof( int) );
pIn[1] = ( int* )malloc( 100 * sizeof( int) );
// assigning value to array.
pIn[0][0] = 23;
pIn[0][1] = 2;
pIn[1][0] = 5689;
pIn[1][1] = 5643;
Process( pIn, 2 ); //calling process funtion
printf(" %d", pIn[1][0]); //printing the changed value by process funtion.
}
You are getting confused because you are using different types when there's no need for such. Arrays follow the same rules of indirection as any other type. If you would allocate a plain int dynamically, you would write int* x = malloc(sizeof(*x));. Simply do the very same thing when it comes to arrays. Don't confuse things by mixing in the "arrays decay to pointers" rule.
So we have int input[2][100], very straight-forward, it is a plain 2D array. Now if you want to allocate that dynamically, you will need a pointer to such an array:
int (*pIn)[2][100]; // pointer to an array of int [2][100].
pIn = malloc(sizeof(*pIn));
And the whole program would then be:
#include <stdlib.h>
void Process (size_t num, int pInput[num][100])
{
}
int main (void)
{
int (*pIn)[2][100];
int input[2][100] = {0};
pIn = malloc(sizeof(*pIn));
if(pIn == NULL)
{
// error handling
return 0;
}
Process(2, *pIn);
Process(2, input);
free(pIn);
return 0;
}
Comments:
size_t is the most correct type to use for array sizes, as it is the type returned by the sizeof operator. So it is just an unsigned integer with a fancy name.
int pInput[num][100] in the function will actually decay into an array pointer to an array of 100 int. You don't need to know that to use it though, simply use pInput[x][y] and pretend it is a 2D array. The important thing here is to understand that the array is not passed by value.
The correct form of main is int main (void).
Casting the result of malloc is pointless.
Always check the result of malloc and remember to clean up allocated data.
I would like to know if there is any way to return an char array.
I tried something like this "char[] fun()" but I am getting error.
I don't want a pointer solution.
Thanks!
You can return an array by wrapping it in a struct:
struct S {
char a[100];
};
struct S f() {
struct S s;
strcpy( s.a, "foobar" );
return s;
}
Arrays cannot be passed or returned by value in C.
You will need to either accept a pointer and a size for a buffer to store your results, or you will have to return a different type, such as a pointer. The former is often preferred, but doesn't always fit.
C functions cannot return array types. Function return types can be anything other than "array of T" or "function returning T". Note also that you cannot assign array types; i.e., code like the following won't work:
int a[10];
a = foo();
Arrays in C are treated differently than other types; in most contexts, the type of an array expression is implicitly converted ("decays") from "N-element array of T" to "pointer to T", and its value is set to point to the first element in the array. The exceptions to this rule are when the array expression is an operand of either the sizeof or address-of (&) operators, or when the expression is a string literal being used to initialize another array in a declaration.
Given the declaration
T a[N];
for any type T, then the following are true:
Expression Type Decays to Notes
---------- ---- --------- -----
a T [N] T * Value is address of first element
&a T (*)[N] n/a Value is address of array (which
is the same as the address of the
first element, but the types are
different)
sizeof a size_t n/a Number of bytes (chars) in array =
N * sizeof(T)
sizeof a[i] size_t n/a Number of bytes in single element =
sizeof(T)
a[i] T n/a Value of i'th element
&a[i] T * n/a Address of i'th element
Because of the implicit conversion rule, when you pass an array argument to a function, what the function receives is a pointer value, not an array value:
int a[10];
...
foo(a);
...
void foo(int *a)
{
// do something with a
}
Note also that doing something like
int *foo(void)
{
int arr[N];
...
return arr;
}
doesn't work; one the function exits, the array arr technically no longer exists, and its contents may be overwritten before you get a chance to use it.
If you are not dynamically allocating buffers, your best bet is to pass the arrays you want to modify as arguments to the function, along with their size (since the function only receives a pointer value, it cannot tell how big the array is):
int a[10];
init(a, sizeof a / sizeof a[0]); // divide the total number of bytes in
... // in the array by the number of bytes
void init(int *a, size_t len) // a single element to get the number
{ // of elements
size_t i;
for (i = 0; i < len; i++)
a[i] = i;
}
arrays aren't 1st class objects in C, you have to deal with them via pointers, if the array is created in your function you will also have to ensure its on the heap and the caller cleans up the memory
A Very very basic code and very very basic explanation HOW TO Return
array back from a user defined function to main function..Hope It
helps!! Below I have given complete code to make any one understand
how exactly it works? :) :)
#include<iostream>
using namespace std;
char * function_Random()
{
int i;
char arr[2];
char j=65;//an ascII value 65=A and 66=B
cout<<"We are Inside FunctionRandom"<<endl;
for(i=0;i<2;i++)
{
arr[i]=j++;// first arr[0]=65=A and then 66=B
cout<<"\t"<<arr[i];
}
cout<<endl<<endl;
return arr;
}
int main()
{
char *arrptr;
arrptr=function_Random();
cout<<"We are Inside Main"<<endl;
for(int j=0;j<2;j++)
{
cout<<"\t"<<arrptr[j];
}
return 0;
}