首页 > 解决方案 > 结构包装器和可变数组大小

问题描述

我经常使用:

  1. 数组包装器按值传递数组,但问题是数组的大小是在编译时确定的(参见代码的第一部分)
  2. 依赖于变量的数组声明(参见代码的第二部分)

如何“组合”这两种类型的代码以具有依赖于变量的数组包装器?(见代码的第三部分。我知道它不能工作,因为结构声明中有一个变量,它只是在这里给出一个想法)

#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);*/

}

标签: c

解决方案


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 constness, 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.


推荐阅读