在 C 中将多维数组作为函数参数传递

编程入门 行业动态 更新时间:2024-10-28 05:18:44
本文介绍了在 C 中将多维数组作为函数参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 C 中,当我不知道多维数组的维数时,我是否可以将多维数组作为单个参数传递给函数?数组将是?

In C can I pass a multidimensional array to a function as a single argument when I don't know what the dimensions of the array are going to be?

此外,我的多维数组可能包含字符串以外的类型.

Besides, my multidimensional array may contain types other than strings.

推荐答案

您可以使用任何数据类型执行此操作.只需将其设为指针:

You can do this with any data type. Simply make it a pointer-to-pointer:

typedef struct { int myint; char* mystring; } data; data** array;

但是不要忘记你仍然需要 malloc 变量,它确实变得有点复杂:

But don't forget you still have to malloc the variable, and it does get a bit complex:

//initialize int x,y,w,h; w = 10; //width of array h = 20; //height of array //malloc the 'y' dimension array = malloc(sizeof(data*) * h); //iterate over 'y' dimension for(y=0;y<h;y++){ //malloc the 'x' dimension array[y] = malloc(sizeof(data) * w); //iterate over the 'x' dimension for(x=0;x<w;x++){ //malloc the string in the data structure array[y][x].mystring = malloc(50); //50 chars //initialize array[y][x].myint = 6; strcpy(array[y][x].mystring, "w00t"); } }

释放结构的代码看起来很相似——不要忘记对你分配的所有东西调用 free()!(此外,在强大的应用程序中,您应该检查 malloc() 的返回.)

The code to deallocate the structure looks similar - don't forget to call free() on everything you malloced! (Also, in robust applications you should check the return of malloc().)

现在假设你想把它传递给一个函数.您仍然可以使用双指针,因为您可能想要对数据结构进行操作,而不是指向数据结构指针的指针:

Now let's say you want to pass this to a function. You can still use the double pointer, because you probably want to do manipulations on the data structure, not the pointer to pointers of data structures:

int whatsMyInt(data** arrayPtr, int x, int y){ return arrayPtr[y][x].myint; }

调用这个函数:

printf("My int is %d. ", whatsMyInt(array, 2, 4));

输出:

My int is 6.

更多推荐

在 C 中将多维数组作为函数参数传递

本文发布于:2023-07-22 03:06:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1183567.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多维   数组   中将   函数   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!