有人可以解释如何在 C 编程中将元素附加到数组吗? [英] Can someone explain how to append an element to an array in C programming?

查看:22
本文介绍了有人可以解释如何在 C 编程中将元素附加到数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我已经习惯了 Python,在 Python 中有一个名为 list.append 的函数,它会自动为您添加一个元素到列表中.C中是否存在这样的函数?

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;

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

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

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

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

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

还要记住,arr 开始于索引 arr[0] 并结束于索引 arr[9] - 10 个元素

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

但是你仍然可以再分配 6 个值,所以当你这样做时

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

arr[4] = 5;

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

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

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

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.

这篇关于有人可以解释如何在 C 编程中将元素附加到数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆