看看下面的调试结果就知道了:
程序代码:
运行结果:
strings指针本身的地址是没变,但查寻数据并不是看指针的地址,而是看指针所指向的位置,即*strings,这个指向已经被改变!这就是指针间接使用数据的陷阱,把地址当作数据。
[ 本帖最后由 TonyDeng 于 2014-9-30 16:55 编辑 ]
程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <conio.h>
#define TRUE 1
#define FALSE 0
void show_memory(const char* const strings[]);
int find_char(const char** strings, int value);
int main(void)
{
const char* arr[] = { "abc", "def", NULL };
show_memory(arr);
if (find_char(arr, 'a'))
{
puts("ok!\n");
}
show_memory(arr);
_getch();
return EXIT_SUCCESS;
}
void show_memory(const char* const strings[])
{
for (size_t index = 0; strings[index] != NULL; ++index)
{
printf_s("%s, %p, %p, %p, %c\n", strings[index], strings[index], strings, *strings, **strings);
}
putchar('\n');
}
int find_char(const char** strings, int value)
{
assert(strings != NULL);
while (*strings != NULL) // 数据入口判断是从*string所指向的位置开始的
{
while (**strings != '\0')
{
if (*(*strings)++ == value) // 在这里修改了*strings的值
{
show_memory(strings);
return TRUE;
}
}
strings++;
}
putchar('\n');
return FALSE;
}
运行结果:
strings指针本身的地址是没变,但查寻数据并不是看指针的地址,而是看指针所指向的位置,即*strings,这个指向已经被改变!这就是指针间接使用数据的陷阱,把地址当作数据。
[ 本帖最后由 TonyDeng 于 2014-9-30 16:55 编辑 ]

授人以渔,不授人以鱼。







