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

8

49

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?

Rudelson answered 6/10, 2014 at 0:55 Comment(4)
array size should be initialized to contain this extra elementSherise
if you have enough memory you can append like this arr[4] = 5 simplySherise
A list and an array are very different types of containers. An array is a contiguous block of memory and if you want to append an element, you have to write it to the position following the last occupied position, provided the array is large enough.Serpens
Do you intend to use an array which grows when you append additional elements? In C++, you could use std::vector but C doesn't offer anything like it. You would have to manually allocate additional memory.Diplostemonous
H
42
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.

Hua answered 6/10, 2014 at 8:42 Comment(4)
Please edit your question to add an explanation of how your code works and how it solves the OP's problem. Many posters on SO are newbies and will not understand the code you have posted.Lithotrity
This isn't the type of appending OP was referring to. Appending is to add to the end of the array without using its index.Disforest
This answer is selected as correct but it's not correct actually. Or is this question was edited after a while so that answer looks like inappropriate?Shaughnessy
Could you use arr[sizeof(arr)+1] = 5;Contemporary
M
5

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.

Moriah answered 6/10, 2014 at 0:58 Comment(5)
The array appears to be declared as int arr[10] which provides plenty of room.Fibril
@GregHewgill: I'm blind, apparently. Thanks.Moriah
The 4th element would be at arr[3] no?Lubbock
@Musa: I count from 0th :)Moriah
While I understand what you mean by '4th' in terms of 0th, 1st, 2nd, 3rd, 4th -- the wording is a bit misleading...Copulative
A
2

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

Anthroposophy answered 6/10, 2014 at 6:26 Comment(1)
After this you can do. if(freePosition<n) arr[freePosition]= x; /* here x is the element to be added at the end of array */Anthroposophy
B
2

For some people which might still see this question, there is another way on how to append another array element(s) in C. You can refer to this blog which shows a C code on how to append another element in your array.

But you can also use memcpy() function, to append element(s) of another array. You can use memcpy()like this:

#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]);
  }

}
Bergsonism answered 9/6, 2020 at 13:0 Comment(1)
Why have you named the arrays first_array and scnd_array but then used a and b?Rebound
S
1

Short answer is: You don't have any choice other than:

arr[4] = 5;
Shaughnessy answered 3/4, 2020 at 7:13 Comment(0)
M
0

If you have a code like int arr[10] = {0, 5, 3, 64}; , and you want to append or add a value to next index, you can simply add it by typing a[5] = 5.

The main advantage of doing it like this is you can add or append a value to an any index not required to be continued one, like if I want to append the value 8 to index 9, I can do it by the above concept prior to filling up before indices. But in python by using list.append() you can do it by continued indices.

Matos answered 9/11, 2018 at 14:29 Comment(0)
T
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 
Tannertannery answered 7/3, 2022 at 15:9 Comment(1)
Your answer is wrong as you allocate a temporary array int arrnew[size] within your function and set an extra value in this array. When the function exits, the arrnew is not valid anymore. Please read other answer for a valid answer and read about scope variables, heap and stack allocation (malloc etc..), this will help you understand better memory managementOverline
S
0

If you want a method that always works, then store the initial size of the array in an int size = 0; variable and increase it every time you append a new element: 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
                      // ...
Sitin answered 9/9, 2023 at 9:14 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.