I'm learning programming for the first time and start with C and work with a German programming book. Unfortunately, the pages in the dynamic memory management section are a bit short and explained quickly, which is why I don't get along very well.
How big is my array?
The size of an Int, but I define array[0] and array[1], how far can I go?
I tried Python briefly back then and there I knew arrays like something like my_Array[1][2] etc and accordingly I could output each thing individually and understood where it was. Here, unfortunately, it does not go into my head at the moment.
Now if I put in array[1] the number 3, then the number 4.
How are the numbers stored here?
Where are they stored?
How can I retrieve every number from array[1]?
If I do realloc(array, array[0]+1), in what way does the 0 field expand from that array?
In my mind, the array was one-dimensional, so that the numbers are lined up as follows:
array[0] = {..,3,4,5,...}
array[1] = {..,3,4,5,...}
And the command always provides only one more place at the end of this array.
I just took the code from the solution now.
Thank you in advance!
#include <stdio.h>
#include <stdlib.h>
int main()
{
int value;
int *array = malloc(sizeof(int));
array[0] = 0;
int i = 1;
while (value >= 0)
{
printf("Enter a positive number to add a nubmer\n");
printf("Or enter a negative number to end.\n");
printf("Enter number: ");
scanf("%i",&value);
if (value >= 0)
{
array = realloc (array, array[0] + 1);
array[i] = value;
i++;
array[0]++;
}
for (int i = i; i <= array[0]; i++)
{
printf("Value %i: %i\n", array[i]);
}
}
free(array);
return 0;```