且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有人可以解释如何在C编程中将元素附加到数组吗?

更新时间:2022-10-16 16:49:26

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

编辑:
所以我被要求解释发生了什么这样做时:

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

您创建一个包含10个元素的数组,并为该数组的前4个元素分配值。 / p>

还要记住, arr 从索引 arr [0] $ c开始$ c>并终止于索引 arr [9] -10个元素

  arr [0]的值为0; 
arr [1]的值为5;
arr [2]的值为3;
arr [3]的值为64;

之后,该数组包含垃圾值/零,因为您没有分配任何其他值



但是您仍然可以分配另外6个值,所以当您这样做

  arr [ 4] = 5; 

您将值5分配给数组的第五个元素。



您可以这样做,直到为 arr 的最后一个索引分配值,即 arr [9] ;



很抱歉,如果我的解释不连贯,但我从来都不擅长解释事物。


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...

I want {0,5, 3, 64, 5} in the end.

I'm used to Python, and in Python there is a function called list.append that appends an element to the list automatically for you. Does such function exist in C?

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.