c - Cannot access variable from two scopes outside the current scope? -
some super easy test codes here elaborate question:
#include <stdio.h> #include <string.h> #include <stdlib.h> void prompt(); void func(); int main() { char* arr = "hello"; while(1) { prompt(); } return 0; } void prompt() { func(); } void func() { char* data = null; data = arr; }
so can see, define variable arr
in main()
function
and code goes inside
while()
loop,in goes inside function called
prompt()
,in goes inside function called
func()
,- in want access variable
arr
defined earlier.
- in want access variable
but, when try compile snippet of code (using gcc), got error telling me
error:'arr' undeclared (first used in function)`.
also, got warning telling me
warning: unused variable 'arr'
.
so weird...any idea?
you have 2 options
make variable arr global (as mentioned sourav)
pass pointer arr variable prompt() function, , func(). can use in func().
which 1 choose depends on task on hand , complexity of project.
if simple project , 1 off, may use global.
however, project complexity increases , if going doing @ multiple locations, suggest take effort , go option 2.
Comments
Post a Comment