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

问题描述 投票:0回答:8

如果我想将一个数字附加到初始化为 int 的数组中,我该怎么做?

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

我最后想要 {0,5,3,64,5}。

我习惯了Python,Python中有一个名为list.append的函数,它可以自动为你将一个元素追加到列表中。 C 里有这样的函数吗?

c arrays integer append
8个回答
40
投票
int arr[10] = {0, 5, 3, 64};
arr[4] = 5;

编辑: 所以我被要求解释一下当你这样做时会发生什么:

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

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

另请记住,

arr
从索引
arr[0]
开始,到索引
arr[9]
结束 - 10 个元素

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

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

但是您仍然可以再分配 6 个值,因此当您这样做时

arr[4] = 5;

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

您可以执行此操作,直到为

arr
的最后一个索引(即
arr[9]
;

)分配值

抱歉,如果我的解释有些断断续续,但我从来不擅长解释事情。


5
投票

将值放入数组的方法只有两种,一种只是另一种的语法糖:

a[i] = v;
*(a+i) = v;

因此,要将某些内容作为索引 4 处的元素,除了

arr[4] = 5
,你别无选择。


3
投票

对于某些可能仍然看到这个问题的人,还有另一种方法可以在 C 中附加另一个数组元素。您可以参考 this 博客,其中显示了如何在

 中附加另一个元素的 C 代码array

但是您也可以使用

memcpy()
函数来附加另一个数组的元素。您可以像这样使用
memcpy()

#include <stdio.h>
#include <string.h>

int main(void)
{

int first_array[10] = {45, 2, 48, 3, 6};
int scnd_array[] = {8, 14, 69, 23, 5};
int i;

// 5 is the number of the elements which are going to be appended
memcpy(first_array + 5, scnd_array, 5 * sizeof(int));

// loop through and print all the array
for (i = 0; i < 10; i++) {
    printf("%d\n", a[i]);
  }

}

2
投票

您可以有一个计数器(freePosition),它将跟踪大小为 n 的数组中的下一个空闲位置。


0
投票

如果您有类似的代码

int arr[10] = {0, 5, 3, 64};
,并且您想要向下一个索引追加或添加值,只需输入
a[5] = 5
即可添加它。

这样做的主要优点是你可以向任何不需要继续的索引添加或附加一个值,就像我想将值

8
附加到索引9一样,我可以通过上面的方法来做到这一点填充指数之前的概念。 但在 python 中,通过使用
list.append()
你可以通过连续索引来做到这一点。


0
投票

简短的答案是: 除了:

你别无选择
arr[4] = 5;

0
投票
void Append(int arr[],int n,int ele){
    int size = n+1; // increasing the size
    int arrnew[size]; // Creating the new array:

    for(int i = 0; i<size;i++){
        arrnew[i] = arr[i]; // copy the element old array to new array:

    }
    arrnew[n] = ele; // Appending the element:
}


by above simple method you can append the value 

0
投票

如果您想要一种始终有效的方法,请将数组的初始大小存储在

int size = 0;
变量中,并在每次追加新元素时增加它:
array[size++] = ...

int array[5];
int size = 0; // you can set the size variable larger 
              // if there are already elements in the array

// append first element
array[size++] = 12;

// append second element
array[size++] = 23;

// append third element
array[size++] = 34;
© www.soinside.com 2019 - 2024. All rights reserved.