http://msdn.microsoft.com/en-us/library/cc262957%28v=office.12%29.aspx
指针:
#pragma once #include <stdio.h> int main(void){
int stopFlag = 0;
int a; int *aPtr; a = 7; aPtr = &a; printf("The address of a is %p\nThe value of aPtr is %p", &a, aPtr); printf("\nThe value of a is %d\nThe value of *aPtr is %d", a, *aPtr); printf("\n\nShowing that * and & are complements of each other\n&*aPtr = %p\n*&aPtr = %p\n", &*aPtr, *&aPtr); scanf("%d", &stopFlag); }
运行结果:
按值传递:
#pragma once #include <stdio.h> int cubeByValue(int n); int main(void){ int stopFlag = 0; int number = 5; printf("The original value of number is %d", number); number = cubeByValue(number); printf("\nThe new value of number is %d", number); scanf("%d", &stopFlag); } int cubeByValue(int n){ return n * n * n; }
运行结果:
按引用传递:
#pragma once #include <stdio.h> void cubeByReference(int *nPtr); int main(void){ int stopFlag = 0; int number = 5; printf("The original value of number is %d", number); cubeByReference(&number); printf("\nThe new value of number is %d", number); scanf("%d", &stopFlag); } void cubeByReference(int *nPtr){ *nPtr = *nPtr * *nPtr * *nPtr; }
运行结果:
最小权限原则(const限定符):
#1 指向非常量数据的非常量指针:
/* using a non-constant pointer to non-constant data */ #pragma once #include <stdio.h> #include <ctype.h> void convertToUppercase(char *sPtr); int main(void){ int stopFlag = 0; char string[] = "characters and $32.98"; printf("The string before conversion is: %s", string); convertToUppercase(string); printf("\nThe string after conversion is: %s", string); scanf("%d", &stopFlag); } void convertToUppercase(char *sPtr){ while(*sPtr != '\0'){ if (islower(*sPtr)){ *sPtr = toupper(*sPtr); } ++sPtr; } }
运行结果:
#2 指向常量数据的非常量指针:
/* using a non-constant pointer to constant data */ #pragma once #include <stdio.h> #include <ctype.h> void printCharacters(const char *sPtr); int main(void){ int stopFlag = 0; char text[] = "print characters of a string"; printf("The string is:\n"); printCharacters(text); printf("\n"); scanf("%d", &stopFlag); } /* sPtr is a "read-only" pointer, cannot modify the character to which it points */ void printCharacters(const char *sPtr){ for (; *sPtr != '\0'; sPtr++){ printf("%c", *sPtr); } }
运行结果:
#3 指向常量数据的非常量指针(企图修改数据):
#4 指向非常量数据的常量指针
/* using a constant pointer to non-constant data */ #pragma once #include <stdio.h> int main(void){ int stopFlag = 0; int x = 0; int y = 0; int* const ptr = &x; printf("The original value of x is: %d", *ptr); x = 5; printf("\nThe new value of x is: %d", *ptr); scanf("%d", &stopFlag); }
运行结果:
#5 指向非常量数据的常量指针(企图修改指针):
#6 指向非常量数据的非常量指针(企图修改数据和指针):