1

I am trying to change the size of a matrix for a graph dynamically.

Code :

void addNumToGraph(vertex** tracker, int inNum, int i, int** graphMatrix)
{
    tracker = (vertex**)realloc(tracker, i*sizeof(vertex*));
    if (sizeof(tracker)/sizeof(vertex*) < inNum)
    {
        graphMatrix = (int**)realloc(graphMatrix, sizeof(int*)*inNum);
        for (i = 0; i < sizeof(graphMatrix)/sizeof(int*); i++)
        {
            //I am getting the error on the line below
            graphMatrix[i] = (int*)realloc(graphMatrix[i], sizeof(int)*inNum);
        }
    }
    tracker[i]->color = 0;
    tracker[i]->distance = -1;
    tracker[i]->father = NULL;
    tracker[i]->value = inNum;
    tracker[i]->index = i;
    }

The function above is being called from a while loop:

while (inChar != '|')
{
    //will scan the vertex number
    scanf("%d", &inNum);
    addNumToGraph(tracker, inNum, i, graph);
    i++;
    //will scan the ','
    scanf("%c", &inChar);
}

which is located in another function.

graph is a local double pointer in the function - I tried two methods: initializing the graph to NULL and initializing it with a malloc so it will not be empty

Both evaluated in the same result:

the error -

"getting error Unhanded exception at (msvcr120d.dll) in Access violation reading location......"

The error appears on the same line of code each time:

graphMatrix[i] = (int*)realloc(graphMatrix[i], sizeof(int)*inNum);

Dos anyone know what I am doing wrong?

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Daniel Fensterheim
  • 371
  • 1
  • 4
  • 8
  • 1
    0) `sizeof(graphMatrix)/sizeof(int*)` wrong. 1)`realloc(graphMatrix[i]`, The extended area has not been initialized. 2) `tracker` and `graphMatrix` is local variable, not update caller side variable. – BLUEPIXY May 28 '15 at 09:50
  • `if (sizeof(tracker)/sizeof(vertex*) < inNum)` : What do you think sizeof(tracker) is here? – dragosht May 28 '15 at 10:10
  • `tracker = (vertex**)realloc(tracker, i*sizeof(vertex*));` This assignment will not be seen by the calling function, since `tracker` is passed by value. Also: you should not cast `XXXalloc()` s retrurn value. – joop May 28 '15 at 11:39

1 Answers1

0

Have you checked that sizeof() is returning you the right values? sizeof doesn't properly report the size of an array when the array is a parameter to a function : http://c-faq.com/aryptr/aryparmsize.html. You can check also here: When a function has a specific-size array parameter, why is it replaced with a pointer?. Correct me if I'm misreading your intentions.

Community
  • 1
  • 1
banach-space
  • 1,781
  • 1
  • 12
  • 27