返回参数不起作用 - 给了我奇怪的错误 [英] Return argument doesn't work — gives me weird error

查看:45
本文介绍了返回参数不起作用 - 给了我奇怪的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is a simple program that should create a substring from a string, then it should return the substring as something that can be printed out. It's actually an exercise and only the substring function can be changed. The problem is that I can't find a return type that doesn't spark all kinds of warnings and errors.

我应该如何更改返回类型?

How should I change the return type?

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 + len); index++)
    {
        if(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().
  • dereferencing a pointer bar that points at already vanished local variable.
  • passing a non-NULL pointer which doesn't point at buffer allocated via malloc(), calloc() or 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;
}

这篇关于返回参数不起作用 - 给了我奇怪的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆