Thread: C: confusing problem with 'for' loops.

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    33

    Confusing problem with 'for' loops.

    The code below is an extract of the main program, as I only need a portion of the program to recreate the problem I'm having.

    If I run this code, the call to 'free' will crash, but only on specific cells, rather than all or none of them.

    What further complicates the problem is on my desktop, the loop will crash on [0][1]. On my netbook, it will crash on [0][2]. Both do use slightly different compilers (netbook uses Dev-cpp 4.xxx, desktop uses Dev-cpp 5.xxx). Could it be Dev-cpp itself that's causing the problem?

    Code:
    #include <stdio.h>
    
    struct cell
    {
        int value;
        struct cell * next;
    } sudokuArray[8][8];
    
    initCell(struct cell * cellPtr, int number)  // Create a linked list, containing numbers 1 to 9, in each array element.
    {
        if (number <= 8)
        {
            cellPtr->next = (struct cell *) malloc(sizeof(struct cell));
            cellPtr->value = number;
            number++;
            initCell(cellPtr->next, number);
        }
        else
        {
            cellPtr->value = number;
            cellPtr->next = NULL;
        }
    }
    
    int main(void)
    {
        int a, b;
        for (a = 0; a <= 8; a++)  // Loop is simply meant to remove head off the linked list for array element.
        {
            for (b = 0; b <= 8; b++)
            {
                initCell(&sudokuArray[a][b], 1);
                printf("Attempting to edit %i, %i\n", a, b);
                struct cell * temp = &sudokuArray[a][b];
                sudokuArray[a][b] = * sudokuArray[a][b].next;
                free(temp);
            }
        }
        getchar();
    
        return 1;
    }
    Last edited by thealmightyone; 02-04-2009 at 05:27 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM
  2. Replies: 5
    Last Post: 11-07-2005, 11:34 PM
  3. half ADT (nested struct) problem...
    By CyC|OpS in forum C Programming
    Replies: 1
    Last Post: 10-26-2002, 08:37 AM
  4. binary tree problem - help needed
    By sanju in forum C Programming
    Replies: 4
    Last Post: 10-16-2002, 05:18 AM
  5. problem with output
    By Garfield in forum C Programming
    Replies: 2
    Last Post: 11-18-2001, 08:34 PM