Skip over navigation

What Are Pointers?

Problems

Pointers and Arrays

How to Cite This SparkNote

Problem : Are pointers and arrays exactly the same thing? Can they be used identically?

For the most part, yes, they can be used almost identically, however they are not exactly the same. An array is often considered to be a constant pointer, meaning that it stores a memory address just like a pointer does but that memory address cannot be changed. The memory pointed to by an array is also static memory (we'll discuss briefly the concept of static and dynamic memory later on). So for example, the following code is valid:

int main()
{
	int steve[100];
	int *spark;
	spark = steve;
	spark[5] = 9;
	printf("%d\n", *(steve + 5));
	return 0;
}
The above code will print out the value 9. However, the following code is NOT valid.

int main()
{
	char steve[100];
	char *spark = "theSpark.com";
	steve = spark;
	printf("%s\n", steve);
}
As steve is an array (a constant pointer) we are unable to assign a different value to it than the one it already has (the address of the array of 100 characters we declared).

Problem : What does the following program do?


int main()
{
	char *p;
	for(p = "WNT"; *p; p++) printf("%c", *p - 1);
	printf("\n");
	return 0;
}

It prints out: VMS

Problem : What does the following program do?


int main()
{
	char *p;
	for(p = "HAL"; *p; p++) printf("%c", *p + 1);
	printf("\n");
	return 0;
}

It prints out: IBM

Problem : Will the following program compile? Will it run?


int main()
{
	char *p;
	p = p + 500;
	return 0;
}

Yes, it will. As long as we don't try to dereference p, it doesn't matter that we're adding to it.

Problem : Does the following code compile? What does it do?


int main()
{
	char word[] = ;
	char *spark[10];
	int i;
	for(i=0; i<10; i) spark[i] = word + (i % 5);
	for(i=0; i<10; i) printf("%c", *spark[i]);
	printf("\n");
	return 0;
}

It does compile, and running it prints: sparkspark

Problem : Write the function: int strlen(char *str) or int strlen(char str[]) that takes a string and returns its length. Write it once using pointer notation and once using array notation.


int strlen(char *str)
{
	int count = 0;
	for(; *str; str) count;
	return count;
}
or

int strlen(char str[])
{
	int count = 0;
	int i;
	for(i=0; str[i]; i) count;
	return count;
}

Problem : Give two names for the second element of the array: int spark[5];

*(spark + 1) and spark[1]

Follow Us