Reputation: 11
I am new to pointers so I tried inventing this simple problem. why is it not working? other than saying what mistake I made I'd greatly appreciate if you guys could tell me an alternative to this method
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int *p;
int i, j;
i = 0;
p = (int *)malloc(sizeof(int) * (i + 1));
scanf("%d", p);
do {
i++;
p = realloc(p, sizeof(int) * i);
scanf("%d", (p + i));
} while (*(p + i) > 0);
for (j = 0; j < i; j++) {
printf("%d\n", *(p + j));
}
free(p);
return 0;
}
Upvotes: 1
Views: 48
Reputation: 311078
This statement
p=(int *)malloc(sizeof(int) * (i+1));
is redundant. It is better to write
p = NULL;
And in a call of scanf use an object of the type int not the pointer.
There can be redundant memory allocation if for example the first entered value will be negative
In this call
scanf("%d", (p+i));
there is an access beyond the allocated memory. You should at least write
scanf("%d", (p + i -1));
It is better to specify an intermediate pointer in this statement
p=realloc(p,sizeof(int)*i);
because the function can return NULL. In this case the address of the previously allocated memory will be lost.
And the condition in the loop
}while(*(p+i)>0);
does not check that the value is not negative.
The program can look the following way
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int *p = NULL;
size_t n = 0;
int value;
for ( int *tmp;
scanf( "%d", &value ) == 1 &&
!( value < 0 ) &&
( tmp = realloc( p, ( n + 1 ) * sizeof( int ) ) ) != NULL;
++n )
{
p = tmp;
*( p + n ) = value;
}
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", *( p + i ) );
}
putchar( '\n' );
free( p );
return 0;
}
If to enter
0 1 2 3 4 5 6 7 8 9 -1
the program output will be
0 1 2 3 4 5 6 7 8 9
Upvotes: 2