[英]return 2D array from C function
Inspired by this question.受到这个问题的启发。 I created this function:
我创建了这个 function:
char** char2Da (int r, int c) {
char (*p)[c] = malloc(sizeof(char[r][c]));
// come code filling 2D array
return (char**) p;
}
Unfortunately it does not work.不幸的是,它不起作用。 Why?
为什么? Is it possible to return a pointer to 2D array in C and preserve [][] notation using method from above?
是否可以使用上述方法返回指向 C 中的二维数组的指针并保留 [][] 符号? If it is not, why?
如果不是,为什么? What am I missing here?
我在这里想念什么?
I know there is workaround by creating outside array, passing it by ref to function.我知道通过创建外部数组,通过引用将其传递给 function 有解决方法。 But its a bit ugly and I would love to encapsulate everything in one function.
但它有点难看,我很想把所有东西都封装在一个 function 中。
Bare in mind that I have PHP and JavaScript background and there you just create arr[][] and return it from function.请记住,我有 PHP 和 JavaScript 背景,您只需创建 arr[][] 并从 function 返回它。 No fuss.
别大惊小怪。
The types char **
and char ( * )[c]
are different types. char **
和char ( * )[c]
类型是不同的类型。 For example dereferencing the first pointer of the type char **
you will get the value stored in first characters of the first row of the allocated array that is not a pointer.例如,取消引用
char **
类型的第一个指针,您将获得存储在分配数组的第一行的第一个字符中的值,该数组不是指针。
You can do the task the following way您可以通过以下方式完成任务
void * char2Da (int r, int c) {
char (*p)[c] = malloc(sizeof(char[r][c]));
// come code filling 2D array
return p;
}
and then in the caller write然后在调用者中写
char ( *p )[c] = char2Da( r, c );
Here is a demonstrative program这是一个演示程序
#include <stdio.h>
#include <stdlib.h>
void * f( size_t r, size_t c )
{
char ( *p )[c] = malloc( sizeof( char[r][c] ) );
return p;
}
int main(void)
{
size_t r = 2, c = 3;
char ( *p )[c] = f( r, c );
free( p );
return 0;
}
Or another demonstrative program.或另一个演示程序。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void * f( size_t r, size_t c )
{
char ( *p )[c] = malloc( sizeof( char[r][c] ) );
char value = 'A';
for ( size_t i = 0; i < r; i++ )
{
memset( p[i], value++, c );
p[i][c-1] = '\0';
}
return p;
}
int main(void)
{
size_t r = 2, c = 3;
char ( *p )[c] = f( r, c );
for ( size_t i = 0; i < r; i++ ) puts( p[i] );
free( p );
return 0;
}
The program output is程序 output 是
AA
BB
If c is a compile-time constant that is you are not allocating a variable length array then the function declaration could look for example like如果 c 是编译时常量,即您没有分配可变长度数组,那么 function 声明可能看起来像
#define C 10
char ( *char2Da (int r ) )[C];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.