Can one (re)set all the values of an array in one line (after it has been initialized)?

前端 未结 4 2121
不思量自难忘°
不思量自难忘° 2021-02-19 13:45

In C, I know I can make an array like this

int myarray[5] = {a,b,c,d,e};

However, imagine the array was already initialised like



        
相关标签:
4条回答
  • 2021-02-19 14:07
    #include<stdio.h>
    #include<stdlib.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 main()
    {
        int *sz=malloc(5*sizeof(int)),i;
    
        //call
        setarray(sz,"10 30");
    
        //output
        for(i=0;i<2;i++)
            printf("%d\n",sz[i]);
    
        return 0;
    }
    
    0 讨论(0)
  • 2021-02-19 14:22
    memcpy(myarray, (int [5]){a,b,c,d,e}, 5*sizeof(int));
    
    0 讨论(0)
  • 2021-02-19 14:22

    Here is a solution that is all standards compatible (C89, C99, C++)

    It has the advantage that you only worry about entering the data in one place. None of the other code needs to change - there are no magic numbers. Array is declared on the heap. The data table is declared const.

    (Click here to try running it in Codepad)

    #include<stdio.h>
    #include<stdlib.h>
    
    int main()
    {
    unsigned int i = 0;
    int *myarray = 0;
    static const int  MYDATA[] = {11, 22, 33, 44, 55};
    
      myarray = (int*)malloc(sizeof(MYDATA));
      memcpy(myarray, MYDATA, sizeof(MYDATA));
    
      for(i = 0; i < sizeof(MYDATA)/sizeof(*MYDATA); ++i)  
      {
        printf("%i\n", myarray[i]);
      }
    
      free(myarray);
    
      return 0;
    }
    
    0 讨论(0)
  • 2021-02-19 14:23

    No, C doesn't have such feature. If you are setting all array elements to the same value use memset(3).

    0 讨论(0)
提交回复
热议问题