Simple C array declaration / assignment question

后端 未结 9 1875
醉话见心
醉话见心 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:59

    #include
    #include
    #include
    
    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;
    }
    

提交回复
热议问题