程序打印垃圾而不是函数调用的实际返回值

mac*_*e_1 0 c printf pointers function return-value

我写了一个算法来从字符串中提取单词并将它们存储在一个数组中,但是我得到了一个不需要的结果,我无法弄清楚为什么.输出是一个非常奇怪的字符.

#include <stdio.h>
#include <windows.h>

char *extract(char *String)
{
char str[10][20];
int x = -1,y = 0,z = 0;
for( size_t n = 0 ; n < strlen(String) ; n++ )
{
    y++;
    if( String[n] == ' ' ) y = 0, z = 0;

    if( y == 1 ) x++;

    if( y > 0 )
    {
        str[x][z] = String[n];
        z++;
        str[x][z] = '\0'; //Comment this*********
    }
}

/*for( int n = 0; n < 10; n++ ) Uncomment this*****
{
    str[n][3] = '\0';
}*/

    return str[7];
}

int main()
{
    printf( "WORD : %s\n",extract("POL POL POL POL POL POL POL POL POL POL") );
    system("PAUSE");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这段代码中的错误在哪里?

注意:当我在其他地方使用printf和strlen时,我也会得到奇怪的字符.

Nat*_*tta 7

我在这里看到的问题str是函数的局部变量extract(),你试图返回它的地址,并使用返回的值作为参数printf().它调用UB.

澄清,str将存在直到extract()完成执行.一旦完成第i个执行并返回给调用者,就不会有任何存在str.因此,返回的指针将指向无效的内存位置.进一步使用该retrun值将导致未定义的行为.