Home > Enterprise >  Using C array to store structs and then trying to read the array using pointer to the first element
Using C array to store structs and then trying to read the array using pointer to the first element

Time:01-12

So I'm using an array to store sructs (struct is Path). Defined as such:

Path **array = malloc(items * sizeof(Path *));

Then each element is alloc'd:

for (i=0;i<items;i  ) 
{
    array[i] = malloc(sizeof(Path *));
}

Later in the program variables are updated as such:

Path *path = array[id];
path->next_hop=-1;
path->weight=INT_MAX;

I then have a separate function to print the values of the array, taking the pointer to the first item in the array (array[0]) and the size of array as parameters, declared as such:

void PrintTable(Path *paths, int n)
{
    if(paths == NULL || n <= 0)
        return;
    printf("%s %8s %8s\n", "Net ID", "Weight", "Next Hop");
    for(int i = 0; i < n; i  )
    {
        Path *p = paths   i;
        printf("%d %8.2f            
  • Related