0

Only two functions in program addValueToArray() which does exactly what its name states and inserts value at a particular row vector.

main() returns EXIT_SUCCESS;

Program prints single instance from first for loop. Can't do the same in second for loop.

I seem to be missing some valuable knowledge on building dynamic matrices and using the malloc() and realloc() functions.


#include <stdio.h>
#include <stdlib.h>

//¡OJO! int* i is a pointer to an object of type int
//      int**  i is a pointer to a pointer to an object of type int
void addValueToArray(int** x, int* count, int index, int value)
{
    int i;
    
    x = malloc(index * sizeof(int*)); //allocate memory sizeof(int* times number of indices)
    
    for(i = 1; i < index ; i++)
    {
        count = realloc(x, i * sizeof(int)); // reallocate new row into x at count[i]
        count[i] = value;                    //assign count[i] value
        printf("%d <--- count at i\n", count[i]); //print value
        break;

        
    }
    
}

int main(void)
{
    int** pX;
    int* rows;
    int j = 10;
    int val = 25;
    
    
    addValueToArray(pX, rows, j, val);
    
    int i;
    
    for(i = 1; i < j; i++)
    {
        printf("%d  <--- count at i\n", rows[i]); //attempting to print value at rows[i]
    }
    return EXIT_SUCCESS;
}


SAMPLE OUTPUT:

25  count at i
1  <--- count at i
2  <--- count at i
3 <--- count at i
4 <--- count at i
5 <--- count at i
  • *"addValueToArray() which does exactly what its name states"* - I don't see how it does exactly what it states. It creates a new array out of thin air, it doesn't add a value to an existing array. What should this function do exactly? Can you be more specific? – Marco Bonelli Jul 29 '20 at 17:16
  • It Dynamically grows the array given to it in the first argument. The value (last argument) is stored in the array at the given index. – Forrest Brown Jul 29 '20 at 18:21

0 Answers0