In C, array indexing is formally defined in terms of pointer arithmetic. We CAN create an array by using pointer only.

Note: This program may cause segmentation fault in some systems.

/* Desc: Using only pointer to create variable and array.
	some system may not work, because of segmentation fault.

Author: Liutong XU
*/
#include<stdio.h>
 
int main()
{
	int a;
	int *p=&a+1;		//p point a's neibough
				//some system may cause segmentation fault

	for (*p=0;*p<10;(*p)++)        //*p used as a loop variable
		scanf("%d",&p[10+*p]); //p+10~p+19 used as an integer array
 
	for (p[0]=0;p[0]<10;p[0]++)    //p[0] is same as *p
		printf("%d\t",p[10+p[0]]); 
 
	return 0;
}

stdin

1 2 3 4 5 6 7 8 9 0

stdout

1   2   3   4   5   6   7   8   9   0

Dynaminc Memory Allocation

Segmentation fault normally is caused by invalid pointer reference, because p+20 may violate other variables.

If we have enough valid memory segment for pointer, then no violation will occur.

/* Desc: Dynamic memory allocation

    dynamically allocated memory may be used as variable or array, 
    but with no common names

Author: Liutong XU
*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
	int *p;        
	p = malloc(20);			//p points to a 20-byte memory

	for (*p=0;*p<10;(*p)++)		//*p used as a loop variable
		scanf("%d",&p[10+*p]);	//p+10~p+19 used as an integer array
 
	for (p[0]=0;p[0]<10;p[0]++)	//p[0] is same as *p
		printf("%d\t",p[10+p[0]]); 
 
	free(p);
	return 0;
}

stdin

1 2 3 4 5 6 7 8 9 0

stdout

1   2   3   4   5   6   7   8   9   0

You have no rights to post comments