顾名思义就是元素为指针的数组,如定义一个 char *类型的指针数组:
char *strName[] = {"123","456","789","abc","def"
};
如果是这样初始化的指针数组,c++编译是会抛出警告信息的:
因为用了字符串常量进行初始化,所以是不可被修改的,所以定义时需要加上 const:
#include <stdio.h>
#include <stdlib.h>char *strName[] = {"123","456","789","abc","def"
};int main()
{printf("strName[1] = %s\n", strName[1]);printf("*strName = %s\n", *strName);printf("*strName+1 = %s\n", *strName+1);printf("sizeof strName[2] = %lu\n", sizeof(strName[2]));return 0;
}
*strName 是解引用,所以输出是 “123” ,而 *strName + 1 为什么输出是 “23” 呢?因为在 *strName 解引用后它的类型是 char*,+1 后即挪动一个 char 长度,指向了“123”中的“2”位置,其实它跟 “123” + 1 的效果是一样的:
#include <stdio.h>
#include <stdlib.h>const char *strName[] = {"123","456","789","abc","def"
};int main()
{printf("strName[1] = %s\n", strName[1]);printf("*strName = %s\n", *strName);printf("*strName+1 = %s\n", *strName+1);printf("\"123\"+1 = %s\n", "123"+1);printf("sizeof strName[2] = %lu\n", sizeof(strName[2]));return 0;
}
如果不用字符串常量初始化,也是可以手动申请内存的,但定义是就不能用const了,如:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>char *strName[3];
int main()
{char buf[16];for(int i = 0; i < 3; i++){strName[i] = new char[16];snprintf(buf, sizeof(buf), "test_%d", i * 10);strncpy(strName[i], buf, 15);}printf("strName[1] = %s\n", strName[1]);printf("*strName = %s\n", *strName);printf("*strName+1 = %s\n", *strName+1);printf("sizeof strName[2] = %lu\n", sizeof(strName[2]));for(int i = 0; i < 3; i++){if(strName[i]){delete strName[i];}}return 0;
}