-1

I define an array and a function. The array is defined outside of the function. But I also have to use this inside the function. What do I need to do?

uint8_t array[] = { 1, 2, 3, 4 };

myfunction(){
   //call index #2 of array
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
M. Zim
  • 1
  • 1
  • 5

1 Answers1

0

Yes, you can do this. The array you declared has global scope, so it is available inside the function.

int arr[] = { 1, 2, 3, 4 };

void myfunction(){
   printf("element is %d",arr[1]); //This is perfectly valid
}
Abhishek Ranjan
  • 498
  • 3
  • 17
  • I am also not the down voter, and I am not sure what compiler you are using, but when I create, and try to use `myfunction` with the form you have, it fails. I am using a C99 compiler. The prototype should be `void myfunction(void);`, (not `void myfunction();`). – ryyker Jun 29 '17 at 20:01
  • @ryyker Are you using a C++ compiler or old C compiler. `void myfunction()` should be OK. – chux - Reinstate Monica Jun 29 '17 at 20:02
  • @chux - I am using a 2017 implementation of C99 (ANSI C), it is a National Instruments implementation. The error msg may be because I have the "require prototypes" option set, and it does not recognize the prototype without the void in the parenthesis. I tried it both ways, it will not compiler without the `void` – ryyker Jun 29 '17 at 20:07
  • 1
    @ryyker [empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters.](https://stackoverflow.com/a/12022875/2410359) may help. – chux - Reinstate Monica Jun 29 '17 at 20:11
  • 1
    @chux - good reference. And I tried it on my system with the prototype: `void func(void);`, but the definition: void func(){...}` and it did not complain. Since this answer is just showing the definition, I agree its perfectly valid. Thanks, – ryyker Jun 29 '17 at 20:17
  • There is nothing like "global scope". – too honest for this site Jun 29 '17 at 22:00
  • @Olaf I wrote it to make him understand that. What I meant was that the array is available globally – Abhishek Ranjan Jun 30 '17 at 05:19
  • @AbhishekRanjan: It is not. You confuse scope and linkage. These are two different fundamental concepts of C. Unless you pointed out their difference, you add to OPs apparent confusion. – too honest for this site Jun 30 '17 at 11:57
  • @Olaf In that case, I request you to edit my answer and all relevant content. It will help OP as well as me. – Abhishek Ranjan Jun 30 '17 at 15:01
  • @AbhishekRanjan: This is not my answer and I will not answer for you; The standard is quite clear and not taht complicated to read. – too honest for this site Jun 30 '17 at 16:06