gpt4 book ai didi

c - typedef 固定长度数组 -> 自动扩展大小?

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:27 25 4
gpt4 key购买 nike

我想定义一个固定长度字符串的结构,像这样:

typedef char str8[8];

因此我可以创建固定长度字符串数组,例如:

str8 * mydata;
mydata = malloc(100 * sizeof(str8));

我正在使用 mydata 来存储名称列表:彼得蜡笔脾气暴躁乐修诺斯测试版...

一切正常,直到 mydata[3] 变为 LexiunosBeta 而不是 Lexiunos。然而,mydata[4] 仍然只是测试版。

这似乎只发生在 size(name) >= size(str8) 时。我将 str8 扩展到 str10 作为临时解决方案,但我真的很想知道真正的问题是什么以及如何解决它。

如果我将 typedef char str8[8] 更改为更可靠的定义,例如:typedef {char * x;}str8;能解决问题吗?

非常感谢大家!

最佳答案

Lexiunos 是 9 个字节,计算尾随的 NUL 并且您的 typedef 是 char[8],您写在数组的边界之外.

查看this thread :

In this particular case, you are declaring a stack based array. Depending upon the particular implementation, accessing outside the bounds of the array will simply access another part of the already allocated stack space (most OS's and threads reserve a certain portion of memory for stack).

堆栈没有“自动扩展大小”之类的东西,使用动态内存:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
char *arr[] = {"Peter", "Waseels", "Grumpy", "Lexiunos", "Beta", /*...*/};
size_t size = sizeof arr / sizeof arr[0];
char **mydata;
size_t i;

mydata = malloc(size * sizeof(*mydata));
for (i = 0; i < size; i++) {
mydata[i] = malloc(strlen(arr[i]) + 1);
if (mydata[i] == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
strcpy(mydata[i], arr[i]);
}
for (i = 0; i < size; i++) {
printf("%s\n", mydata[i]);
free(mydata[i]);
}
free(mydata);
return 0;
}

关于c - typedef 固定长度数组 -> 自动扩展大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37042673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com