从 C 函数返回字符串 [英] Returning string from C function

查看:26
本文介绍了从 C 函数返回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经 3 年多没用过 C 语言了,我对很多东西都生疏了.

I haven't used C in over 3 years, I'm pretty rusty on a lot of things.

我知道这可能看起来很愚蠢,但我目前无法从函数返回字符串.请假设:我不能为此使用 string.h.

I know this may seem stupid but I cannot return a string from a function at the moment. Please assume that: I cannot use string.h for this.

这是我的代码:

#include <ncurses.h>

char * getStr(int length)
{   
    char word[length];

    for (int i = 0; i < length; i++)
    {
        word[i] = getch();
    }

    word[i] = '';
    return word;
}

int main()
{
    char wordd[10];
    initscr();
    *wordd = getStr(10);
    printw("The string is:
");
    printw("%s
",*wordd);
    getch();
    endwin();
    return 0;
}

我可以捕获字符串(使用我的 getStr 函数),但我无法正确显示它(我得到垃圾).

I can capture the string (with my getStr function) but I cannot get it to display correctly (I get garbage).

感谢您的帮助.

推荐答案

要么在调用方的堆栈上分配字符串并将其传递给你的函数:

Either allocate the string on the stack on the caller side and pass it to your function:

void getStr(char *wordd, int length) {
    ...
}

int main(void) {
    char wordd[10 + 1];
    getStr(wordd, sizeof(wordd) - 1);
    ...
}

或者在getStr中将字符串设为静态:

Or make the string static in getStr:

char *getStr(void) {
    static char wordd[10 + 1];
    ...
    return wordd;
}

或者在堆上分配字符串:

Or allocate the string on the heap:

char *getStr(int length) {
    char *wordd = malloc(length + 1);
    ...
    return wordd;
}

这篇关于从 C 函数返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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