【问题标题】:How to use different temporary strings in a C loop?如何在 C 循环中使用不同的临时字符串?
【发布时间】:2014-02-11 21:20:32
【问题描述】:

我正在使用小型 C API 进行开发,我需要创建一个结构数组,每个结构都有不同的标题。根据我的 PHP 背景,我编写了以下代码摘录:

char *title = "";
for(int w = 0; w < total_workouts; w++) {
    snprintf(title, 10, "Workout %c", workouts[w].letter);
    workout_menu[w] = (SimpleMenuItem) { .title = title };
}

但是,title 变量作为指向SimpleMenuItem 对象的指针发送,因此所有菜单项都具有相同的标题。我花了一些时间摆弄字符串数组等,但无法让它工作。

如何修复代码的 sn-p 以使每个菜单项(for 中的每个段落)都有不同的字符串指针?

【问题讨论】:

  • 代码需要title 的空间吗? snprintf() 需要尺寸吗?
  • 抱歉,清理了我不小心删除了发送到 snprintf 的代码。它已修复,但这不是问题的最初根源。

标签: c c-strings pebble-watch


【解决方案1】:

在循环内部动态地为标题创建一些空间

workout_menu[w].title = (char *)malloc(sizeof(char) * 10);

然后使用sprintf/snprintf直接复制到SimpleMenuItem的title成员中(不是局部变量)

sprintf(workout_menu[w].title, "Workout %c", workouts[w].letter)

请记住在完成后使用 free(),以免发生内存泄漏。

【讨论】:

  • 旁注,我没有验证您如何调用 snprintf 等。这只是假设您的其余代码有效的修改。
  • 看起来不错,但后来我得到了这个...error: passing argument 1 of 'snprintf' discards 'const' qualifier from pointer target type
  • 这是因为你使用 snprintf 错误,就像我说我没有验证它:) linux.die.net/man/3/snprintf 注意参数不匹配你的 - 我更新它使用 sprintf,因为你不需要“ n" 变体
  • snprintf(workout_menu[w].title, sizeof workout_menu[w].title, "Workout %c", workouts[w].letter)?
  • chux - sprintf 没有大小。 int sprintf(char *str, const char *format, ...);
猜你喜欢
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多