c - static variable scope inside and outside the function -


please notice static variable selection. testing if selection assigned correct char string within different scope.

#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 output selection here, selection random char, not 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 output selection here, prints correct char string "srfpro".     // what's difference between scope , above scope?     printf("acode_prockey: %s\n", selection);  }  int main () {     acode_prockey();     // output srfpro, first token of char text[].     printf("main: %s\n", selection);   }    

i hoping can explain global static varible "selection". when printf inside function "display_ecnt_codes", outputs random char. if not printf inside function, output correct char in main function.

in following function, returning pointer not valid after function returns.

static char* sel_item(char* text) {     char* pch;      // array on stack     char buf[80];     strcpy(buf, text);      // pointer element of array.     pch = strtok(buf, " ");      // returns pointer not valid after function returns.     return pch; } 

later on, use invalid pointer stored in selection. program exhibits undefined behavior because of that.


Comments

Popular posts from this blog

how to do line continuation in perl debugger for entering raw multi-line text (EOT)? -

javascript - Create websocket without connecting -

sharepoint - Accessing files across a shared directory using a Windows service -