/* * Various exercises with pointers, arrays, and dynamic allocation * (meant to illustrate language issues; not necessarily anything that * would be directly useful in your own code; but if you can trace and * understand this you're doing great!) * CSE303 demo program au07 */ #include #include void swap(void** p1, void** p2) { void* tmp = *p1; *p1 = *p2; *p2 = tmp; } void client() { int* ip1 = (int*)malloc(sizeof(int)); *ip1 = 17; int* ip2 = (int*)calloc(1,sizeof(int)); swap((void**)&ip1,(void**)&ip2); int* ipArray = (int*)malloc(*ip2 * sizeof(int)); // size 17 array int i; for(i=0; i < *ip2; ++i) ipArray[i]=i; // technically WRONG (int and void* not necessary the same size) // but works on attu and many other systems where ints and pointers // are both 32 bits swap((void**)&ipArray[3],(void**)ipArray+9); // two ways to pointing elements printf("%d %d\n",*ip1,*ip2); for(i=0; i < *ip2; ++i) printf("%d ", ipArray[i]); printf("\n"); // a way to _kind of_ check that the WRONG thing we did will probably work if(sizeof(int) != sizeof(void*)) fprintf(stderr,"uh-oh!"); } int main(int argc, char**argv) { client(); return 0; }