Hi,
I am total new in C. I have an array, then i loop it to get array elements. How can i add this array element into existing array? thank!

char arr[] = {1};

for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++ ) {
something happend here = arr[i];
}

printf("Result: %i:%i", arr[0], arr[1]); // Result: 1:1 (<- is equal to: char arr[] = {1,1};)

Edited 6 Years Ago by tenix: n/a

Arrays don't grow or shrink. If you need dynamic sizing, use an std::vector instead. In fact, you should prefer std::vector in favor of arrays anyway, because they're easier to work with.

[edit: Bah! This is the C forum. Ignore this post]

Edited 6 Years Ago by Narue: n/a

Are you trying to dynamically size the array with malloc or calloc?

"something happened here" is a complete mystery to me.

First if you want to dynamically enlarge the array you should use malloc and calloc, which dynamically reserves memory while the program is running.

If you want to insert values to an array, you should have the array element at the right side of the expression like "arr = something;".

You should reserve some space in the memory when you declare an array like "char arr[arraySize]" if you want to insert ( actually assign values to existing array elements ) values to the array.


main()
{
int i;
int arraySize = 10;
char myArray[ arraySize ] = {'a'};
for( i=1; i < arraySize; i++)
myArray[i] = ( char )i;

return;
}
This question has already been answered. Start a new discussion instead.