今天,我问我,char **
对象是如何保存在内存中或二进制文件中的。我使用以下代码片段对其进行了测试:
char **array = (char *)malloc(3 * sizeof(char *));
array[0] = "Foo"; // Length: 3
array[1] = "Long string"; // Length: 11
array[2] = "Bar"; // Length: 3 => Full length: 17
int length = 17;
我将此数组写入文件:
FILE *file = fopen(...);
fwrite(array, length, 1, file);
fclose(file);
很棒的是,当我使用以下代码从文件中再次读取此数组时,成功读取了字符串长度,而不会保存超过 17 个字节。
FILE *file = fopen(...);
int length = 17;
char **array = (char *)malloc(length);
int index = 0;
int parsedLength = 0;
while (parsedLength < length)
{
char *string = array[index];
int stringLength = strlen(string);
printf("%i: \"%s\" (%i)\n", index, string, stringLength);
parsedLength += stringLength;
++index;
}
我得到的输出等于:
0: "Foo" (3)
1: "Long string" (11)
2: "Bar" (3)
编译器如何知道数组中的每个字符串有多长?