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.

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

  1. make variable arr global (as mentioned sourav)

  2. 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

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -