c - 定义字符串数组
问题描述
为什么以下是初始化字符串数组的可接受方法:
char * strings[] = { "John", "Paul", NULL};
但是这种方式会失败:
char ** strings = { "John", "Paul", NULL};
我的想法是它的工作方式与以下操作相对相同:
char string[] = "John";
char * string = "Paul";
两者都工作的地方。两者有什么区别?
解决方案
char * strings[]
is an array of pointers. When you initialize it as
char * strings[] = { "John", "Paul", NULL};
the strings John
Paul
are string literals. They are constants that exist somewhere in the code or Read only memory. What is done is to copy the pointer to the string literal John
into the strings[0]
and so on. i.e.
strings[0] --> holds a pointer to "John".
strings[1] --> holds a pointer to "Paul"
Note that the string literals should not be modified by your program. If you do, it is undefined behaviour.
In case of char ** strings
This is a pointer to a pointer. It is a single memory location and cannot hold many pointers on its own. So, you cannot initialize it as below.
char ** strings = { "John", "Paul", NULL}; // error
However, a pointer to pointer can be used along with dynamic memory allocation (malloc
,calloc
etc) to point to an array of strings.
char string[] = "John";
In this case, you have a char array into which the string literal is copied. This step is done by the compiler, generally in the start up code before the main starts.
char * string = "Paul";
Here you have a char pointer which points to a string literal.
Difference between the above two statements is that in the case of a char array, you can modify the elements of string
but you cannot in the second case.
推荐阅读
- jquery - 使用 jquery 规则确认密码不起作用
- uwp - 在 UWP 中检测 Windows 10 S-Mode
- android - 尝试在 Windows 上执行本机应用程序时出错
- protractor - 如何在茉莉花框架(量角器)中使用无限循环?
- opencart - 从一个站点重定向到另一个站点
- html - bootstrap 4轮播相同高度,适用于不同图像尺寸和屏幕尺寸
- php - Zoho JSON 结果转换为 CSV 文件
- azure - 如何在 Azure 应用服务的响应标头中隐藏服务器参数?
- c# - 文本文件中的分隔行
- javascript - 在 Window 和 MacOS 上的电子应用程序中禁用键盘快捷键 Alt + Tab