Simple C array declaration / assignment question

后端 未结 9 1877
醉话见心
醉话见心 2021-01-05 06:13

In higher level languages I would be able something similar to this example in C and it would be fine. However, when I compile this C example it complains bitterly. How can

相关标签:
9条回答
  • 2021-01-05 06:58

    In C99, using compound literals, you could do:

    memcpy(values, (int[3]){1, 2, 3}, sizeof(int[3]));
    

    or

    int* values = (int[3]){1, 2, 3};
    
    0 讨论(0)
  • 2021-01-05 06:58

    This works and optimizes better under gcc with -O3 (the compiler completely removes the code), whereas the memcpy forces the memory to be copied in all cases.

    template <typename Array>
    struct inner
    {
        Array x;
    };
    
    
    template <typename Array>
    void assign(Array& lhs, const Array& rhs)
    {
        inner<Array>& l( (inner<Array>&)(lhs));
        const inner<Array>& r( (inner<Array>&)(rhs));
        l = r;
    }
    
    int main()
    {
        int x[100];
        int y[100];
    
        assign(x, y);
    }
    
    0 讨论(0)
  • 2021-01-05 06:59
    #include<stdio.h>
    #include<stdlib.h>
    #include<stdarg.h>
    
    int *setarray(int *ar,char *str)
    {
        int offset,n,i=0;
        while (sscanf(str, " %d%n", &n, &offset)==1)
        {
            ar[i]=n;
            str+=offset;
            i+=1;
        }
        return ar;
    }
    
    int *setarray2(int *ar,int num,...)
    {
       va_list valist;
       int i;
       va_start(valist, num);
    
       for (i = 0; i < num; i++) 
            ar[i] = va_arg(valist, int);
       va_end(valist);
       return ar;
    }
    
    int main()
    {
        int *size=malloc(3*sizeof(int*)),i;
        setarray(size,"1 2 3");
    
        for(i=0;i<3;i++)
            printf("%d\n",size[i]);
    
        setarray2(size,3 ,4,5,6);
        for(i=0;i<3;i++)
            printf("%d\n",size[i]);
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题