RedRidingHood
RedRidingHood

Reputation: 592

Realloc fails in loop

I want to read a number as an array of int, but something strange happens.

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

int getNumber( int ** dst )
{
    int size = 0;
    int num = 0;

    scanf( "%c", &num );
    while( num != 10 )
    {
        if( (num < 48) || (num > 57) )
        {
            printf( "This is not a number.\r\n" );
            return -1;
        }
        size++;

        *dst = ( int * ) realloc( *dst, sizeof( int ) * size );
        *dst[ size - 1 ] = ( num - 48 );

        scanf( "%c", &num );
    }

    return size;
}

int main()
{
    int * number = NULL;
    int size = 0;

    size = getNumber( &number );

    return 0;
}

First iteration passes normally, but on the second iteration *dst[ size - 1 ] = ( num - 48 ); fails. What is wrong?

Upvotes: 0

Views: 187

Answers (2)

RedRidingHood
RedRidingHood

Reputation: 592

Oh, I found it!
The problem was in the feature of handling dereferencing operators.
Square brackets have a higher priority than asterisk.
Because of it, if I modify that line:
*dst[ size - 1 ] = ( num - 48 );
Like that:
(*dst)[ size - 1 ] = ( num - 48 );
It will work properly!

Upvotes: 2

ayusha
ayusha

Reputation: 484

because [ ] has higher precedence than * operator.so it behaves like *(dst[size-1])
instead of (*dst)[size-1].

Upvotes: 2

Related Questions