Question

I would like to know why I can't reach to increase my array size by only one in a while loop. Here is my code :

void pb_memory(void){
    printf("ERROR : memory problem !\n");
    system("PAUSE");
    exit(EXIT_FAILURE);
}

int main(int argc, char *argv[])
{
             int length = 0;
            /*allocate memory and check for no error*/
            int *array = calloc(1, sizeof(int)); /*initialize to 0*/
            if(array == NULL)
                     pb_memory();

            /*Check for valid inputs and put into array*/
            while((scanf("%d", &num)) != EOF){
                               array[length]=num;
                               length++;
                               array = realloc(array, length*sizeof(int));
                               if(array == NULL)
                                        pb_memory();
            }
.
.
.
.

}

Why is this not working ? It fails and goes directly into the pb_memory() function .I would like every time length increase by one my array does too...

Thanks for your help.

EDIT : Sorry guys I wanted to keep the code simple and focused on my problem that's why I didn't write all my variables. Anyway I'm learning for next time and thanks @Michael and everyone who participate.

Était-ce utile?

La solution

You are trying to access to a bad index array[length]=num;, if the size of array is length, you can't access to length-th element.

You have to move the write after the reallocation :

/*Check for valid inputs and put into array*/
while((scanf("%d", &num)) != EOF){
  length++;
  array = realloc(array, length*sizeof(int));
  if(array == NULL)
    pb_memory();
  array[length-1]=num;
}

Autres conseils

Just some thoughts: 1. include some print statements to see exactly where the code fails 2. run gdb with the output the program. For example, in a CLI, run the command "gdb ./a.out" 3. Where is the variable "num" declared ? It suddenly appears in the while-loop's condition ?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top