在C中分配字符串的形式是正确的?
char *sample;
sample = malloc ( length * sizeof(char) );
Run Code Online (Sandbox Code Playgroud)
要么
sample = malloc ( length * sizeof(char*) );
Run Code Online (Sandbox Code Playgroud)
为什么占用1个字节char*需要4个char字节?
假设目标是存储一串length字符,正确的分配是:
sample = malloc(length + 1);
Run Code Online (Sandbox Code Playgroud)
笔记:
sizeof (char),因为它始终为1,它不会添加任何值.length是字符串的可见字符的长度,strlen()即将返回length.malloc().原因char *更大的是它是指针类型,指针几乎总是大于单个字符.在许多系统(例如你的系统)上,它们是32位,而字符只是8位.由于指针需要能够表示机器内存中的任何地址,因此需要更大的尺寸.在64位计算机上,指针通常是64位,即8个字符.