c - 结构包装器和可变数组大小
问题描述
我经常使用:
- 数组包装器按值传递数组,但问题是数组的大小是在编译时确定的(参见代码的第一部分)
- 依赖于变量的数组声明(参见代码的第二部分)
如何“组合”这两种类型的代码以具有依赖于变量的数组包装器?(见代码的第三部分。我知道它不能工作,因为结构声明中有一个变量,它只是在这里给出一个想法)
#include <stdio.h>
int main() {
// First part of code
// Array wrapper to pass array by value but size of array is determined at compile time
struct S {int m_array[5];} myarray={1,2,3,4,5};
struct S myarraycopy;
struct S copyarray(struct S a) { return a ;}
myarraycopy=copyarray(myarray);
for (int i=0;i<5;i++) printf("%d \n",myarraycopy.m_array[i]);
// Second part of code
// Array declaration is function of a variable n and
// so it is not determined at compile time
int n;
printf("Size : ");scanf("%d",&n);
int myarray1[n];
for (int i=0;i<n;i++) myarray1[i]=i;
printf("Array size %d \n",sizeof(myarray1));
for (int i=0;i<n;i++) printf("%d \n",myarray1[i]);
/* How to combine the two parts above ???
int n1;
printf("Size : ");scanf("%d",&n1);
struct S1 {int m_array[n1];} myarray1;
struct S1 myarraycopy1;
struct S1 copyarray1(struct S1 a) { return a ;}
myarraycopy1=copyarray1(myarray1);*/
}
解决方案
How is it possible to "combine" these two types of code to have array wrappers that depends of a variable ?
You cannot, at least in standard C. In the standard's terms, the members of a structure type cannot be variably-modified. This serves the purpose that the size of a structure type is always a compile-time constant (even, technically, structure types having flexible array members).
In the general case, you have the alternative of passing your array normally, in the form of a pointer to its first element. You may declare the function parameter as a pointer to const
elements, so that the function cannot modify the array (at least, not without casting away the const
ness, which you could surely persuade your compiler to warn about).
That does not serve your copyarray()
use case, because you cannot return arrays (as such) either, nor assign to whole arrays. But memcpy()
does that job fine without need for wrapping or passing around arrays by value, so the case seems contrived.
推荐阅读
- reactjs - 如何使选中的图标突出显示
- firebase - 在本机反应中,我如何等待 redux 命令更改存储以完成执行,然后再触发 firebase 上的更新
- java - 方法不允许 HTTPS spring
- javascript - 如何编辑和更改/重命名标题(反应)
- python - 构造一个有向网络的二分表示,用于 networkx 中的 hopcroft-karp 匹配函数
- sql - ORA-01861: 值与格式字符串不匹配
- wpf - WPF ListBox - 以编程方式更改项目的背景颜色
- reactjs - 使用 redux 和 table 显示来自多个端点的数据
- python - Discord.py "Bot 对象没有属性 'move_member'
- regex - 使用 awk - reg 表达式重命名 fasta 标题