将值追加到c数组

将值追加到c数组,c,arrays,C,Arrays,这是一个非常简单的问题,但我不知道怎么做 例如,我有一个名为array的数组,其中包含[1,2,3,4,5,6],我想向数组中添加第七个值7,使其包含[1,2,3,4,5,6,7] 有这样的功能吗?我需要包括任何额外的头文件吗?如有任何帮助,我们将不胜感激。如果它是一个声明如下的普通数组: int Array[] = {1,2,3,4,5,6}; 那么你就不能给它添加更多的值了。如果事先提供了一些空间,则可以添加更多值: int Array[7] = {1,2,3,4,5,6}; Array[

这是一个非常简单的问题,但我不知道怎么做

例如,我有一个名为
array
的数组,其中包含
[1,2,3,4,5,6]
,我想向数组中添加第七个值
7
,使其包含
[1,2,3,4,5,6,7]


有这样的功能吗?我需要包括任何额外的头文件吗?如有任何帮助,我们将不胜感激。

如果它是一个声明如下的普通数组:

int Array[] = {1,2,3,4,5,6};
那么你就不能给它添加更多的值了。如果事先提供了一些空间,则可以添加更多值:

int Array[7] = {1,2,3,4,5,6};
Array[6] = 7;

如果你使用C++,我建议使用STD::vector,但是它不存在于C.< /P>

NOPE。在C语言中,没有存储关于数组大小或占用元素数量的信息。您可以设计一个结构和一个过程来实现这一点,但该语言并不适合您

struct cvector
{
    int *content;
    int occupied;
    int size;
};

void cvector_init(struct cvector *v)
{
    v->content = malloc(sizeof *(v->content) * 16;
    v->size = 16;
    v->occupied = 0;
}

void cvector_kill(struct cvector *v)
{
    free(v->content);
}

// returns true if an error occurred, as is the style with linux syscalls.
int cvector_append(struct cvector *v, int value)
{
    if (v->occupied == v->size)
    {
        int new_size = v->size * 1.75;
        int *new_content = realloc(v->content, new_size);
        if (new_content == NULL) return 1;
        v->content = new_content;
        v->size = new_size;
    }
    v->content[v->occupied++] = value;
    return 0;
}

为此,您需要使用
中的malloc和realloc函数。基本思想是预先分配一定数量的空间,然后在发现阵列不够大时扩大阵列。

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

int *append(int size, int a[size], int value){
    int *ret = malloc((size+1)*sizeof(int));
    memcpy(ret, a, size*sizeof(int));
    ret[size] = value;
    return ret;
}
int main(void){
    int Array[] = {1,2,3,4,5,6};
    int size = sizeof(Array)/sizeof(*Array);
    int *a = append(size++, Array, 7);
    int i;
    for(i=0;i<size;i++){
        printf("%d\n", a[i]);
    }
    free(a);
    return 0;
}
#包括 #包括 int*append(int-size,int-a[size],int-value){ int*ret=malloc((大小+1)*sizeof(int)); memcpy(ret,a,size*sizeof(int)); ret[大小]=值; 返回ret; } 内部主(空){ int数组[]={1,2,3,4,5,6}; int size=sizeof(数组)/sizeof(*数组); int*a=append(大小++,数组,7); int i;
对于(i=0;iIt不可能或动态添加元素)在声明数组时大小已确定。因此,可以预先留出大小,并留有可添加的边距,以便复制和添加,作为由
malloc(calloc或realloc)保护的数组区域的替代方案
。这是令人困惑的。连续调用
append
,这是内存泄漏。此外,为什么不从开始使用指针,然后直接使用
realloc
?@undur\u gong或连续调用append,这是内存泄漏。这当然是错误的用法。为什么不从开始使用指针,然后直接使用realloc?这是错误的是因为假定传递了一个数组。是的,这是真的。但是您并没有附加到数组中。至少有一些解释说明您正在做什么以及如何使用
append
。@undur\u gongor在数组中添加更改大小的元素不能是注释。This是的代码示例,作为在注释中使用该malloc的数组的替代。