Why is the array not getting properly initialized?
Code:#include<stdio.h>
main(void)
{
int *p = malloc(5 * sizeof(int));
int i=0;
while(i<5)
{
*p = i;
i++;
p++;
}
i=0;
while(i<5)
{
printf("a[%d] = %d\n",i,*p);
i++;
}
getchar();
return(0);
}
Printable View
Why is the array not getting properly initialized?
Code:#include<stdio.h>
main(void)
{
int *p = malloc(5 * sizeof(int));
int i=0;
while(i<5)
{
*p = i;
i++;
p++;
}
i=0;
while(i<5)
{
printf("a[%d] = %d\n",i,*p);
i++;
}
getchar();
return(0);
}
You are shifting the pointer's position in the first while loop and in the second while loop, you are accessing memory you shouldn't access. That's really bad. Do not use pointer arithmetics, prefer using the brackets [] instead with i as an index.
Edit: Besides, it's int main() and not just main() or void main().
You also didn't include stdlib.h either.
ok!, it is working now, thanx