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

后端 未结 6 526
轻奢々
轻奢々 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:20

    int arr[10] = {0, 5, 3, 64};
    arr[4] = 5;
    

    EDIT: So I was asked to explain what's happening when you do:

    int arr[10] = {0, 5, 3, 64};
    

    you create an array with 10 elements and you allocate values for the first 4 elements of the array.

    Also keep in mind that arr starts at index arr[0] and ends at index arr[9] - 10 elements

    arr[0] has value 0;
    arr[1] has value 5;
    arr[2] has value 3;
    arr[3] has value 64;
    

    after that the array contains garbage values / zeroes because you didn't allocated any other values

    But you could still allocate 6 more values so when you do

    arr[4] = 5;
    

    you allocate the value 5 to the fifth element of the array.

    You could do this until you allocate values for the last index of the arr that is arr[9];

    Sorry if my explanation is choppy, but I have never been good at explaining things.

提交回复
热议问题