代码之家  ›  专栏  ›  技术社区  ›  Stef1611

结构包装器和可变数组大小

c
  •  0
  • Stef1611  · 技术社区  · 6 年前

    我经常使用:

    1. 依赖于变量的数组声明(参见代码第二部分)

    #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);*/
    
    }
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   John Bollinger    6 年前

    如何将这两种类型的代码“组合”成依赖于变量的数组包装器?

    你不能,至少在标准C中是这样。在标准的术语中,结构类型的成员不能被可变地修改。这样做的目的是结构类型的大小总是一个编译时常量(即使从技术上讲,结构类型具有灵活的数组成员)。

    在一般情况下,您可以选择以指向其第一个元素的指针的形式正常传递数组。可以将函数参数声明为指向 const 元素,以便函数无法修改数组(至少,在不丢弃 你可以说服你的编译器去警告它)。

    这不适合你 copyarray() memcpy() 如果不需要按值包装或传递数组,那么这项工作做得好吗?因此,这种情况似乎是人为的。

        2
  •  -1
  •   Stef1611    6 年前

    但是,正如我们所知的myarray1的大小( sizeof(S1)+n1*sizeof(int) ),我想知道是否可以使用代码中的内联汇编语言来强制复制整个变量myarray1。

    #include <stdio.h>
    
    typedef struct {int l;int m_array[];}S1;
    void myfoo(S1 a) {
        for (int i=0;i<a.l;i++) a.m_array[i]*=10;
        printf("in myfoo\n");
        for (int i=0;i<a.l;i++) printf("%d \n",a.m_array[i]);
    }
    
    int main() {
    
    int n1;
    printf("Size : ");scanf("%d",&n1);
    S1 *myarray1=malloc(sizeof(S1)+n1*sizeof(int));
    
    myarray1->l=n1;
    for (int i=0;i<n1;i++) myarray1->m_array[i]=i;
    
    myfoo(*myarray1);
    printf("in main\n");
    for (int i=0;i<n1;i++) printf("%d \n",myarray1->m_array[i]);
    }