c - 修改结构中的 char *
问题描述
我正在尝试通过遇到一些问题来修改结构中的 char *。
#define MAXLINELENGTH 1000
#define MAXINSTRUCTIONS 65536
struct labelMem {
char *name;
int pc;
};
struct labelStr {
struct labelMem labels[MAXINSTRUCTIONS];
};
while (func(string s) == 0) {
strncpy(programLabels.labels[labelCounter].name, label, MAXLINELENGTH);
labelCounter++;
}
我尝试了几种不同的方式将我的结构排列在一个数组中,但每次我在修改我的 char * var 时遇到问题。
任何有关如何解决此问题的想法将不胜感激。
解决方案
没有调用malloc
指针实际上并不指向任何东西。
您需要在使用指针之前为其分配内存。您可以将程序更改为
while (func(string s) == 0) {
// Allocate memory and check for errors
programLabels.labels[labelCounter].name = malloc (strlen (label) + 1);
if (!programLabels.labels[labelCounter].name) { /* handle error */ }
strncpy(programLabels.labels[labelCounter].name, label, MAXLINELENGTH);
labelCounter++;
}
推荐阅读
- pygame - 在pygame中实现非常基本的重力
- sql - 从同一个线程多次调用 sub
- javascript - 嵌套对象值不遵循从 ajax 调用到 actionmethod 的参数
- javascript - 使用 webpack 将所有 js 文件构建到目标文件夹
- c++ - 使用 Gstreamer 进行文本渲染(appsrc、textrender)
- thymeleaf - Thymeleaf 文本模板中的条件表达式
- python - 将集成终端 VSCode 的输出更改为 windows cmd 提示符
- java - 获取对 FXML ImageView 的引用
- php - 从ajax表单提交中获取空值
- python - Flask 依赖注入