-3

I am making a program in C and need to be able to input data into an array which will clear on every restart but the array seems to be full of random data and I’m not able to input my own data. This is what I am doing to store the numbers:

int RentSmall[30];
int RentMedium[20];
int RentLarge[25];

I’m then calling it with:

printf("The small shoes that are rented are\n");
    for(int i = 0; i < 30; ++i) {
    printf("%d\n", RentSmall[i]);
}

Any help would be greatly appreciated.

I have tried to use other int names and the same result is happening so I must be missing something.

Biffen
  • 6,249
  • 6
  • 28
  • 36
lid5050
  • 1
  • 1
  • 2
    In C, arrays _are_ full of random data until you initialize them. – dandan78 Apr 21 '23 at 09:47
  • Just initialize the arrays: `int RentSmall[30] = {0,};`. You don't need to initialize every element. One will do. – Adrian Mole Apr 21 '23 at 09:49
  • 2
    Does this answer your question? [How to initialize all members of an array to the same value?](https://stackoverflow.com/questions/201101/how-to-initialize-all-members-of-an-array-to-the-same-value) – Biffen Apr 21 '23 at 09:49
  • You speak about inputs. You use `printf()`. It is `scanf()` for inputs. – dalfaB Apr 21 '23 at 09:49
  • You can provide an explicit initialiser: `int array[SomeSize] = { 0 };` intialising the first view values with those provided and the remaining ones with zeros. You even can have dedicated initialisers: `int array[SomeSize] = { [12] = 10, [10] = 12] };` – again, values not provided are set to 0, including those in gaps between the initialisers. Note, though, that you can *not* provide initialiser lists to VLA. – Aconcagua Apr 21 '23 at 09:50

1 Answers1

2

You can initilaize all the values in your arrays to 0 like this:

int RentSmall[30] = {0};

If you want to give each of them a different value you would do it like this:

int RentSmall[30] = {5, 12, 0, 1, 4}; // and so on for each element

If you dont specify all elements, like I did, the remaining elements will be set to 0.

If you want to set them later on you can loop through each of them:

for (int i = 0; i < 30; i++)
{
    RentSmall[i] = 0;    // or whatever value you want to give it
}
RentSmall[6] = 3; // or just set a single one

For input from the user you would use the scanf() function like this:

scanf("%d", &RentSmall[0]);

The %d stands for integer values and the &RentSmall[0] is the address of the value u want to read from the user input.

Joel
  • 721
  • 1
  • 13
  • I will give this a go later on and then update will using scanf for inputting to the array allow for 30 numbers to be added (maximum of 30) if not i will crack on with working out a way around it so it changes position in the array each time thank you for the help also – lid5050 Apr 21 '23 at 09:56
  • @lid5050 if you have a new question, ask a new question and don't update this one. – Jabberwocky Apr 21 '23 at 10:12