Home > Net >  Is it possible to pass a global char variable as a parameter in a function?
Is it possible to pass a global char variable as a parameter in a function?

Time:10-27

So I have a global variable called char words[10]. I would like to pass it as a parameter as in a function.

This is the code I have so far and it does not compile obviously. I just do not know how exactly to pass the words variable to the function read_words.


#include <stdio.h>

char *words[10];

void read_words(*words){
}


int main(){

  read_words(*words);
}

CodePudding user response:

Consider this: If it's global, do you still need to pass it to your function?

Then there's the question of style regarding global variables but that's another topic.

CodePudding user response:

To anwser you question directly: Yes, you can pass a global variable to a function.

However often there is not a need to. This is beacuse any function in the same file as the decloration char* words[10]; will be able to reference it. Futhermore if you create new files and #include your current file, functions in the new files will also be able to access words.

Another note: To make your program run you have to use pointers correctly, here is a short intro to pointers. If you want words to be an array of pointers, you want to pass it to a function as a pointer to a pointer. This modified version of your code should compile:

#include <stdio.h>

char *words[10];

void read_words(char ** words){
}


int main(){

  read_words(words);
}

This is my first ever answer so feel free to correct me where I am wrong.

  • Related