网上一篇文章 char** 和char[][]的问题引发的讨论, 这里做个笔记。
以下内容部分为网上引用整理。
#includeusing namespace std; int output(char **buf){ printf(" buf address: %p\n",buf); printf("&buf[0] address: %p\n",&buf[0]); printf("&buf[1] address; %p\n",&buf[1]); printf("*buffer address: %p\n",*buf); printf(" buf[0] address: %p\n",buf[0]); printf(" buf[1] address: %p\n",buf[1]); printf(" *buf hex: %lx\n",*buf); printf(">>> %x%x%x%x%x%x%x%x\n",'b',' ','a',' ','m','a',' ','i'); printf(">>> %lx\n",buf[0]);/** 错误 0的说明 * 函数内buf为二级指针,buf[0]类型char*,为指针,64位系统指针8字节, * 则buf[0]指针的值为buf所指内存单元向下共8个内存单元内容组成的值。 * 这8个内存单元内容是什么呢,就是从函数外buf[0][0]即字符'i'的地址 * 开始依次取八个字节得到的是'i am a b',将其转化为数值即为0x6d612069, * 故buf[0]的值为0x6d612069(注意little endian),printf(“%s\n”,buffer[0]),故发生地址越界。 * * 也就是相当于将char *p = "i am a bastard..." 强制转换为char **pp = (char**)p, * 然后取pp[0], pp[0]就是p的前8个字节。 *//** * 错误 0: 执行这句会Crash *///printf(">>> %s\n",buf[0]); printf("\n\n"); } int main() {char buffer[100][1024] = {0};char *a ="i am a bastard...";char *b ="hello world...";int len1 = sprintf(buffer[0],a);int len2 = sprintf(buffer[1],b); buffer[0][len1] ='\0'; buffer[1][len2] ='\0';/************** 0 ***************/ { printf(" buffer address: %p\n",buffer); printf(" buffer hex: %x\n",buffer); printf(" &buffer[0] address: %p\n",&buffer[0]); printf(" &buffer[1] address: %p\n",&buffer[1]); printf("&buffer[0][0] address: %p\n",&buffer[0][0]); printf("a address: %p\n",a); printf(" a string: %s\n",a); printf(" a hex: %lx\n",a); printf("buffer[0]: %s\n",buffer[0]); printf("buffer[1]: %s\n",buffer[1]); printf(" a hex: ");for (int i =0; i