Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain how to append an element to an array in C programming?

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?

like image 321
user3326078 Avatar asked Oct 06 '14 00:10

user3326078


People also ask

Can we append in array?

If you are using List as an array, you can use its append(), insert(), and extend() functions. You can read more about it at Python add to List. If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array.

What does it mean to append an array?

Array#append() is an Array class method which add elements at the end of the array. Syntax: Array.append() Parameter: – Arrays for adding elements. – elements to add. Return: Array after adding the elements at the end.


3 Answers

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.

like image 184
bitcell Avatar answered Oct 16 '22 22:10

bitcell


There are only two ways to put a value into an array, and one is just syntactic sugar for the other:

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

Thus, to put something as the element at index 4, you don't have any choice but arr[4] = 5.

like image 34
Amadan Avatar answered Oct 16 '22 21:10

Amadan


You can have a counter (freePosition), which will track the next free place in an array of size n.

like image 2
Arjun Prasad Avatar answered Oct 16 '22 23:10

Arjun Prasad