C pointers for dummies (like me :)

Martin Zeller ANSI C 0 Comments

Just a little piece of code in C for clearing up pointers… look at the comments in the first part!
(If you need an environment to develop in C on windows, find a solution here: environment for ansi c on windows

void change(short*, short*);

int main(void) {
	short *pointer1 = NULL;
	short *pointer2 = NULL;
	short value1 = 1111;
	short value2 = 2222;

	pointer1 = &value1;
	pointer2 = &value2;

	printf("main - VALUE1:\n");
	printf("main - value of value1: %d\n", value1); // Output the value of value1
	printf("main - value of value1: %d\n", *pointer1); // Output the value at the address
	printf("main - address of value1: %p\n", &value1); // Output the address of value1
	printf("main - address of value1: %p\n", pointer1); // Output the value of pointer1 (it's the address of value1 !)
	printf("main - address of pointer1: %p\n", &pointer1);	// Output the address(!) of the pointer(!)
	printf("\nmain - VALUE2:\n");
	printf("main - value of value2: %d\n", value2);
	printf("main - value of value2: %d\n", *pointer2);
	printf("main - address of value2: %p\n", &value2);
	printf("main - address of value2: %p\n", pointer2);
	printf("main - address of pointer2: %p\n", &pointer2);
	printf("\n*** main - starting change...\n\n");
	change(pointer1, pointer2);
	printf("\n*** main - changing done!\n\n");
	printf("main - VALUE1:\n");
	printf("main - value of value1: %d\n", value1);
	printf("main - value of value1: %d\n", *pointer1);
	printf("main - address of value1: %p\n", &value1);
	printf("main - address of value1: %p\n", pointer1);
	printf("main - address of pointer1: %p\n", &pointer1);
	printf("\nmain - VALUE2:\n");
	printf("main - value of value2: %d\n", value2);
	printf("main - value of value2: %d\n", *pointer2);
	printf("main - address of value2: %p\n", &value2);
	printf("main - address of value2: %p\n", pointer2);
	printf("main - address of pointer2: %p\n", &pointer2);

	return EXIT_SUCCESS;
}

void change(short *valuePointer1, short *valuePointer2) {
	printf("change - value of value1: %d\n", *valuePointer1);
	printf("change - address of value1: %p\n", valuePointer1);
	printf("change - value of value2: %d\n", *valuePointer2);
	printf("change - address of value2: %p\n", valuePointer2);
	printf("change - changing now...\n");
	short h;
	h = *valuePointer1;
	*valuePointer1 = *valuePointer2;
	*valuePointer2 = h;
	printf("change - changing done!\n");
	printf("change - value of value1: %d\n", *valuePointer1);
	printf("change - address of value1: %p\n", valuePointer1);
	printf("change - value of value2: %d\n", *valuePointer2);
	printf("change - address of value2: %p\n", valuePointer2);
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.