c - 结构指针未按预期保存字符数组
问题描述
typedef struct _Text {
char *str;
int length;
int counter;
} *Text;
int main(void) {
Text txt= malloc(sizeof(Text));
char *txtStr="hi";
txt->str=txtStr;
return 0;
}
该结构根本无法按预期工作,给定的 char 数组在检查时未正确保存。
解决方案
typedef struct Text {
char *str;
int length;
int counter;
} Text;
更好读
接着
int main(void) {
Text *txt = malloc( sizeof( Text ));
txt->str = malloc( sizeof( char ) *3);
strcpy( txt->str, "hi" );
printf("%s\n", txt->str );
return 0;
}
推荐阅读
- python-3.x - 我需要从该 url 从表中提取数据并将它们放入表中并导出到 csv
- vba - excel VBA如何在函数中返回2个不同的数组
- python - 如何使用python从字符串中删除.ds模式字符串
- android - Android Studio 失败:“文件已删除,但在缓存中找不到以前的版本”
- python - sklearn 中梯度提升的基础学习者
- microservices - 当两个微服务托管在同一台机器上与分布式时,它们如何进行通信?
- android - Android Room @field 是什么意思
- git - 设置 GIT 和 CICD 多个 Shopify 站点
- ios - 如何通过 ios UITest 中的 testID 获取 React Native TextInput
- r - 使用 [[ vs [ 和 NULL 列出索引