Can someone explain how to append an element to an array in C programming?

后端 未结 6 524
轻奢々
轻奢々 2021-02-05 03:55

If I want to append a number to an array initialized to int, how can I do that?

int arr[10] = {0, 5, 3, 64};
arr[] += 5; //Is this it?, it\'s not working for me.         


        
6条回答
  •  逝去的感伤
    2021-02-05 04:41

    For some people which might still see this question, there is another way on how to append another array element(s) in C. You can refer to this blog which shows a C code on how to append another element in your array.

    But you can also use memcpy() function, to append element(s) of another array. You can use memcpy()like this:

    #include 
    #include 
    
    int main(void)
    {
    
    int first_array[10] = {45, 2, 48, 3, 6};
    int scnd_array[] = {8, 14, 69, 23, 5};
    
    // 5 is the number of the elements which are going to be appended
    memcpy(a + 5, b, 5 * sizeof(int));
    
    // loop through and print all the array
    for (i = 0; i < 10; i++) {
        printf("%d\n", a[i]);
      }
    
    }
    

提交回复
热议问题