返回一个char指针数组 [英] Returning an array of char pointers

查看:77
本文介绍了返回一个char指针数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将char*的数组返回给函数.我已将代码简化为一个测试用例,该用例可以克隆一个char数组,而不是包含char来保存指向这些char的指针.

I'm trying to return an array of char*'s to a function. I've simplified my code to a test case that clones a char array that instead of containing chars holds pointers to those chars.

/*
 * code.c
 */
#include <stdio.h>

char* makePointerCopy(char cIn[]);

int main() {
    char cTest[] = {'c', 't', 's', 't'};
    char* cPTest[] = makePointerCopy(cTest);
    printf("%p %c", cPTest, *cPTest);
    fflush(stdout);
    return 0;
}

char* makePointerCopy(char cIn[]) {
    char* cOut[sizeof(cIn)/sizeof(cIn[0])];
    int iCntr;

    for (iCntr = 0; iCntr < sizeof(cIn)/sizeof(cIn[0]); iCntr++)
        cOut[iCntr] = cIn + iCntr;

    return cOut;
}

除了一些警告,这是编译器必须对此代码段说的话:

A couple of warnings aside, this is what the compiler has to say about this code snippet:

无效的初始化程序(位于char* cPTest[] = makePointerCopy(cTest);)

为什么会这样?

推荐答案

因为makePointerCopy返回char*,而不是char*[].

您应该可以将该行更改为:

You should be able to change that line to:

char* cPTest = makePointerCopy(cTest);

更具体地说,您收到该错误消息而不是有关类型的信息的原因是,数组初始化程序必须是编译时常量.

More specifically, the reason that you get THAT error message, rather than something about types, is that array initializers are required to be compile-time constants.

来自 http://bytes.com/topic/c/answers/215573 -invalid-initializer

即使声明没有记录在案 范围,在两个C90中都将是非法的 和C99. C90需要编译时间 常量自动初始化器 并注册数组.而且C90和 C99需要一个字符数组 初始化为a)字符串文字, 或b)用大括号括起来的初始值设定项 列表.

Even if the declaration is not at file scope, it would be illegal in both C90 and C99. C90 demands compile-time constant initializers for automatic and register arrays. And both C90 and C99 require a character array to be initialized with a) a string literal, or b) a brace-enclosed initializer list.

仍然,类型不匹配是这里的实际问题.

Still, the type mismatch is the actual problem here.

这篇关于返回一个char指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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