函数返回结构编译因gcc而失败,但因vc6.0而成功

函数返回结构编译因gcc而失败,但因vc6.0而成功,c,gcc,C,Gcc,为什么gcc无法编译,但vc6.0却成功了 gcc版本4.1.2 20070115 SUSE Linux linux:~# cc t.c t.c: In function ‘main’: t.c:24: error: invalid use of non-lvalue array - printf((confFQDNtolower(&tFQDN)).strName); 守则: #include <stdio.h> #include <ctype.h> typ

为什么gcc无法编译,但vc6.0却成功了

gcc版本4.1.2 20070115 SUSE Linux

linux:~# cc t.c
t.c: In function ‘main’:

t.c:24: error: invalid use of non-lvalue array - printf((confFQDNtolower(&tFQDN)).strName);
守则:

#include <stdio.h>
#include <ctype.h>

typedef struct  {
    char strName[128];
    unsigned short wLen;
}T_FQDN;

T_FQDN confFQDNtolower(T_FQDN *ptFQDN)
{
    static T_FQDN tFQDN = {0};
    int i;

    tFQDN.wLen = ptFQDN->wLen;
    for (i = 0; i < ptFQDN->wLen; i++)
    {
        tFQDN.strName[i] = tolower(ptFQDN->strName[i]);
    }

    return tFQDN;
}

int main()
{
    T_FQDN tFQDN = {"a.B.c", 5};

    printf((confFQDNtolower(&tFQDN)).strName);

    return 0;
}

我认为应该按照以下方式更改代码

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

typedef struct  {
    char *strName;
    unsigned short wLen;
}T_FQDN;

T_FQDN confFQDNtolower(T_FQDN *ptFQDN)
{
    static T_FQDN tFQDN = {NULL,0};
    int i;

    tFQDN.wLen = ptFQDN->wLen;

    if(!tFQDN.strName) free(tFQDN.strName);
    tFQDN.strName = strdup(ptFQDN->strName);


    for (i = 0; i < ptFQDN->wLen; i++)
    {
        tFQDN.strName[i] = tolower(tFQDN.strName[i]);
    }


    return tFQDN;
}

您只需更改printf行:

printf("%s", (confFQDNtolower(&tFQDN)).strName);
以上内容适用于GCC和VisualStudio的CL编译器。

请尝试

printf(&(confFQDNtolower(&tFQDN).strName[0]));
请参阅此处接受的答案和评论,以了解这会改变情况的原因。
这不是C++。它是C。适用于GCC 4.8.2。您使用什么版本?为什么要设计这样的函数来接受非常量指针并返回值?您是否正在积极尝试设计尽可能不直观的界面?那样的话,干得好此外,您的代码没有复制字符串终止符,因此打印生成的strName将生成未定义的行为。OP为什么要这样做?我想不出一个好的理由来说明这是一个好主意。如果OP的版本确实有效,那么您的版本也不会用于OP。