c - 从函数 : Error 返回字符串指针

标签 c linux gcc string

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
char** parser(char *message)
{
    char a[9][256];
    char* tmp =message;
    bool inQuote=0;
    int counter=0;
    int counter2=0;
    while(*tmp!='\0')
    {
        switch(*tmp)
        {
            case ',': if(!inQuote)
                   {    
                    a[counter][counter2]='\0';
                    printf("A[%d]: %s\n",counter,a[counter]);
                    counter++;
                    counter2=0;
                    }

                  break;
            case '"':
                inQuote=!inQuote;
                break;
            default:
                a[counter][counter2]=*tmp;
                counter2++;
                break;
        }
    tmp++;

    }
        a[counter][counter2]='\0';
        printf("A[%d]: %s\n",counter,a[counter]);
        return(a);

}
int main()
{
    char **a = parser("N,8545,01/02/2011 09:15:01.815,\"RASTA OPTSTK 24FEB2011 1,150.00 CE\",S,8.80,250,0.00,0");
    return 0;
}

给出的错误在第 38 行:从不兼容的指针类型返回函数返回局部变量的地址

编辑 有人可以相应地修改代码,以便我可以(通过指针)从 main() 访问“a”的内容;

最佳答案

错误不言自明

Line 38 : return from incompatible pointer type

a 已被定义为 char a[9][256]。因此,在语句 return(a); 中,返回值的类型是 char (*)[256](指向 256 个字符的数组的指针)而不是char **(根据 parser() 的原型(prototype))

function returns address of local variable

嗯,a 是函数的局部变量。你不应该返回局部变量的地址(除非它的内存是动态分配的或者它是一个静态变量)

关于c - 从函数 : Error 返回字符串指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5015972/

相关文章:

c - 将二进制 blob 与 GCC 链接时的奇怪行为

c - 在 C 中不使用函数原型(prototype)有什么好处吗?

c - C 中的双重检查锁定模式问题

C 正确使用 free

c - POSIX:在 64KB 边界上分配 64KB

linux - Nagios check_ntp_peer 不工作

linux - 使用 grep 提取值

c - 无法识别的调试选项 : 1 [enabled by default]

在 Windows 上使用 C 清除命令提示符

c++ - gcc 可以使我的代码并行吗?