返回参数不起作用 – 给我一些奇怪的错误

这是一个应该从字符串创建子字符串的简单程序,然后它应该将子字符串作为可以打印出来的东西返回。 它实际上是一个练习,只能改变子串函数。 问题是我找不到不会引发各种警告和错误的返回类型。

我该如何更改退货类型?

static void panic(const char *serror) { printf("%s", serror); exit(1); } static void *xmalloc(size_t size) { void *ptr; if (size == 0) panic("Size is 0!\n"); ptr = malloc(size); if (!ptr) panic("No mem left!\n"); return ptr; } static char *substring(const char *str, off_t pos, size_t len) { char out [len]; int index; for(index = 0; index = pos && index < (pos + len)) { out[index - pos] = str[index]; } } return out; } int main(int argc, char **argv) { char *foo = "Nicht\n"; char *bar = substring(foo, 2, 3); printf("%s", bar); free(bar); return 0; } 

你调用了两个未定义的行为

  • 取消引用指向已消失的局部变量的指针bar
  • 传递非NULL指针,该指针不指向通过malloc()calloc()realloc()分配的缓冲区。

另请注意

  • 您必须通过添加空字符来终止字符串。
  • 你的循环效率不高。

更正的代码:

 static char *substring(const char *str, off_t pos, size_t len) { char *out = xmalloc(len + 1); int index; for(index = pos; index < (pos + len); index++) { out[index - pos] = str[index]; } out[len] = '\0'; return out; }