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); }
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.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
ok!, it is working now, thanx