有人能解释一下如何在C编程中向数组追加元素吗?

kcwpcxri  于 9个月前  发布在  其他
关注(0)|答案(8)|浏览(54)

如果我想给一个初始化为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中是否存在这样的函数?

zbq4xfa0

zbq4xfa01#

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]分配值;
抱歉,如果我的解释是起伏不定的,但我从来没有善于解释的事情。

vhipe2zx

vhipe2zx2#

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

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

因此,要将某个元素作为索引为4的元素,除了arr[4] = 5之外别无选择。

rm5edbpk

rm5edbpk3#

对于一些仍然看到这个问题的人来说,还有另一种方法可以在C中添加另一个数组元素。您可以参考this博客,其中展示了如何在array中追加另一个元素的C代码。
但是你也可以使用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]);
  }

}
v7pvogib

v7pvogib4#

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

uqdfh47h

uqdfh47h5#

如果你有一个像int arr[10] = {0, 5, 3, 64};这样的代码,并且你想在下一个索引中追加或添加一个值,你可以简单地通过输入a[5] = 5来添加它。
这样做的主要优点是,你可以添加或追加一个值到任何不需要继续的索引中,比如如果我想将值8追加到索引9中,我可以在索引之前填充上面的概念。但是在python中,通过使用list.append(),你可以通过连续索引来实现。

uqzxnwby

uqzxnwby6#

**简单的回答是:**你别无选择:

arr[4] = 5;
ee7vknir

ee7vknir7#

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
jtoj6r0c

jtoj6r0c8#

如果你想要一个总是有效的方法,那么将数组的初始大小存储在一个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

array[size++] = 12;   // append 1. element
array[size++] = 23;   // append 2. element
array[size++] = 34;   // append 3. element
                      // ...

相关问题