为什么我需要函数中的char数组使用“static”?

时间:2018-02-17 12:24:34

标签: c

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

char* test_static_char(int n);

int main()
{    
    printf("calling through 1: %s \n", test_static_char(1));    
    printf("calling through 2: %s \n", test_static_char(2));    
    printf("calling through 3: %s \n", test_static_char(3));

    return 0;
}

char* test_static_char(int n)
{        
    static char test_char[4];    
    test_char[0] = '\0';

    switch(n)
    {
        case 1: strcat(test_char,"A");
                strcat(test_char,"B");
                strcat(test_char,"C");
                break;


         case 2: strcat(test_char,"D");
                 strcat(test_char,"E");
                 strcat(test_char,"F");
                 break;

         default: strcat(test_char,"G");
                  strcat(test_char,"H");
                  strcat(test_char,"I");    
    }    

    return test_char;    
}

只有当我向char数组添加“static”时才会得到所需的结果。 但我不知道为什么。我认为它应该像我期望的那样没有“静态”,因为  ,每次调用该函数时,都会使用test_char [4],就像之前从未使用过一样。另外,当我不使用静态时,我收到此警告消息 ,“fuction返回局部变量的地址”

<The desired result>
calling through 1: ABC

calling through 2: DEF

calling through 3: GHI

0 个答案:

没有答案