there may be three mistake in this code
int val, x;
int *ptr;
ptr = malloc(sizeof(int)); //mistake 1
do
{
scanf("%d", &val);
*ptr = val;
ptr++; //mistake 2
}while(val < 20);
for(x=0; x<5; x++) //Print values *ptr, mistake 3
{
printf("ptr[%d]: %d\n", x, *ptr);
ptr++;
}
- let's look into No.1:
ptr = malloc(sizeof(int)); this line will cause a compile time error error: assigning to 'int *' from incompatible type 'void *'
so we should write as ptr = (int*)malloc(sizeof(int));
Besides there is a terrible mistake, we discuss this in No.2.
No.2
you only malloc sizeof(int) bytes memory, and use it for more than sizeof(int) bytes.
No.3
the ptr increased every time our program get input value. But ptr never comes back to when printf begins.
This code may be work or not, as programer often says "this cause undefined behavior". Because we use some memory we didn't malloc.
int val, x;
int *ptr;
int *ptr_origin;
ptr = malloc(sizeof(int));
ptr_origin = ptr;
do
{
scanf("%d", &val);
*ptr = val;
ptr++;
}while(val < 20);
ptr = ptr_origin;
for(x=0; x<5; x++) //Print values *ptr
{
printf("ptr[%d]: %d\n", x, *ptr);
ptr++;
}
And this final version should be work.
int val, x, total, total2;
int *ptr;
int *ptr_origin;
scanf("%d", &total); // specific input value counts
total2 = total;
if (total <= 0)
{
printf("invalid count\n");
return 0;
}
ptr = malloc(sizeof(int)*total);
ptr_origin = ptr;
do
{
scanf("%d", &val);
*ptr = val;
ptr++;
}while(--total > 0);
ptr = ptr_origin;
for(x=0; x<total2; x++) //Print values *ptr
{
printf("ptr[%d]: %d\n", x, *ptr);
ptr++;
}
UPDATE: as Iskar Jarak comment, this is C not C++ question. No.1 will not be a problem.