Deep understanding of C pointer Reading Notes, deep understanding of pointers
Chapter5.h
# Ifndef _ CHAPTER_5 _ # define _ CHAPTER_5 _/* Study Notes for deep understanding of the C pointer-Chapter 5 * // * strings that should not be modified should use const char * de-modifier */size_t _ strlen_test (const char *); /* several methods for returning strings */char * _ return_str _ test (); # endif
Chapter5.cpp
# Include "Chapter5.h" # include <stdio. h> # include <stdlib. h> # include <time. h> # include <string. h> size_t _ strlen_test (const char * pstr) {size_t length = 0;/* because the parameter is modified with const, In the function, we cannot change the string pointed to by the pointer. Otherwise, a compilation Error * // * pstr = 'A' is generated. Here, the compilation error while (* pstr ++) ++ length is returned; return length;}/* return several methods of the string */char * _ return_str _ test () {/* The first method returns a literal constant, because this is a nominal value constant, it is stored in the constant storage area and disappears when the program ends, no problem with the returned address * // * srand (time (NULL); int num = rand () % 2; if (num % 2 = 0) return "even number"; elsereturn "odd number"; * // * method 2 returns the address pointed to by the dynamic memory because the address is allocated in the heap, it disappears only when the programmer releases the memory. Therefore, the address of the returned memory will not be faulty * // * char * p_str = (char *) malloc (sizeof (char) * 16); strcpy (p_str, "DLUTBruceZhang"); return p_str; * // * The third method returns a static string, this string is stored in the static storage area, that is, the location where global variables are stored. This memory will disappear only when the program ends, no problem with the returned address * // * static char str [] = "DLUTBruceZhang"; return str; * // * method 4 first, this is an incorrect method. It returns the address of a local variable. This memory is stored in the stack. When the function returns, this memory will be overwritten by other values, that is, the address to be stored is not the desired value. We need to avoid it in the Program */* char _ str [] = "DLUTBruceZhang"; return _ str; */}