thr*_*ruh 4 c arrays string performance char
我有一个关于以下空间效率的具体问题:
假设您要声明一个由 7 个字符串文字组成的数组,它们表示彩虹的 7 种颜色(即红色、橙色、黄色、绿色、蓝色、靛蓝和紫色)。假设一个指针的大小是 8 个字节,那么声明一个二维字符数组还是一个不规则的字符串数组在空间上更有效?
C 中的字符串让我感到困惑,我不确定我是否马上要解决这个问题。任何帮助将不胜感激,特别是即使使用少量代码进行演示。谢谢大家!
编辑: 我编写了以下代码:
#include <stdio.h>
#include <string.h>
int main(void) {
char *string_array[] = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"};
char char_array[][7] = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"};
printf("\nThe size of a string is: %lu", sizeof(char *));
printf("\nThe size of a string array with the given data is: %lu", sizeof(string_array));
printf("\nThe size of a char is: %lu", sizeof(char));
printf("\nThe size of a char array with the given data is: %lu", sizeof(char_array));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出以下内容:
The size of a string is: 4
The size of a string array with the given data is: 28
The size of a char is: 1
The size of a char array with the given data is: 49
Run Code Online (Sandbox Code Playgroud)
我不确定我是否正确地做到了这一点,因为我预计第一个数组(不规则的字符串数组)会更大?
选项1:
const char *colors = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"};
Run Code Online (Sandbox Code Playgroud)
这里所有的字符串都占用了它们需要的只读内存(43字节),但是额外的56字节(8 个字节的 7 个指针)用于将 7 个指针存储在内存中,99总共产生字节。
选项 2:
const char colors[][7] = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"};
Run Code Online (Sandbox Code Playgroud)
这里声明了一个 2D 数组,但由于您需要在编译时声明第 2 维,因此它必须足够大以容纳数组中最长的字符串(每个字符串中的 +1 个字节用于空终止字节)。因此,您最终会在所有较短的字符串上浪费空间。
在这里,49总共分配了字节(7 个字节的 7 个字符串),但是为了存储所有字符串,您只需要43字节 - 因此“浪费”了 6 个字节。
总而言之,第二个选项需要更少的内存。