簡體   English   中英

函數內外的靜態變量范圍

[英]static variable scope inside and outside the function

請注意靜態變量selection 我正在測試是否在不同范圍內為選擇分配了正確的char字符串。

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

static char* selection;

static char* sel_item(char* text)
{
    char* pch;
    char buf[80];
    strcpy(buf, text);
    pch = strtok(buf, " ");
    return pch;
}

static int display_ecnt_codes(char* text)
{   
    char buf[80];
    strcpy(buf, text); 
    selection = sel_item(buf);
    // why if I output the selection here, the selection is random char, not the correct char "SRFPRO".
    // printf("display_ecnt_codes: %s\n", selection); 
}

int acode_prockey()
{
    char text[] = "SRFPRO - Surface Protection (DealerProduct)";
    display_ecnt_codes(text); 
    // why if I output the selection here, it prints the correct char string "SRFPRO".
    // what's the difference between this scope and the above scope?
    printf("acode_prockey: %s\n", selection); 
}

int main ()
{
    acode_prockey();
    // it will output SRFPRO, the first token of the char text[].
    printf("main: %s\n", selection);  
}   

我希望有人可以解釋全局靜態變量“選擇”。 當我在函數“display_ecnt_codes”中打印它時,它會輸出隨機字符。 如果我不在函數內打印它,它會在main函數中輸出正確的char。

在以下函數中,您將返回一個在函數返回后無效的指針。

static char* sel_item(char* text)
{
    char* pch;

    // An array on the stack
    char buf[80];
    strcpy(buf, text);

    // A pointer to some element of the array.
    pch = strtok(buf, " ");

    // Returns a pointer that is not valid after the function returns.
    return pch;
}

稍后,您將使用存儲在selection中的無效指針。 因此,您的程序會顯示未定義的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM