Home > Software design >  How to add items into array?
How to add items into array?

Time:10-19

Hello I'm new to C language and I have created a for loop to generate bunch of numbers between Dmin and Dmax. Now I want to add these numbers to my array in for loop. How can I overcome that ? Any tips ?

double size = 50.00;
double length;
double deltaX;
length = Dmax - Dmin;
deltaX = length / size;

double array[size];

printf("%lf", deltaX);

for(double i = Dmin; i < size; i =deltaX)
{
    array[i   1];
}

CodePudding user response:

First, as pointed out by Ted in the comments, I would change the type of size to be an integral type, e.g. int.

Next, I would also change the variable i to be an integral type as well since it used to index the array.

Finally, you should modify your array to assign a value into each indexed position array[i] inside your for loop. I would also recommend following Willis's advice in the comments and use a mathematically equivalent loop instead.

Example:

double x = Dmin;
for(int i = 0; i < size; i  )
{
    array[i] = x;
    x  = deltaX;
}

CodePudding user response:

  1. Array sizes must be integral - you can declare size as an integer type and everything will still work as expected:
    size_t size = 50;
    ...
    double array[size];
    
  2. You're wanting to assign the i'th value between dMin and dMax to the i'th element of the array - that would look something like this:
    for ( size_t i = 0; i < size; i   )
      array[i] = dMin   i * deltaX;
    
    so your array will contain
    array[0] <- dMin
    array[1] <- dMin   deltaX
    array[2] <- dMin   2 * deltaX
    ...
    

Once defined, an array cannot be resized - if you define it to hold 50 elements, it will only ever be able to hold 50 elements. Arrays do not automatically grow if you attempt to assign outside that range, nor will you get an index out-of-range exception or anything like that. You'll just wind up overwriting some other bit of memory that may or may not be important.

  •  Tags:  
  • c
  • Related