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

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]

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;
}

Thank you all your help!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.