The predefined array C

In C, when defining an array, I can do the following:

int arr[] = {5, 2, 9, 8};

      

And so I defined it and filled it in, but how do I define it in my .h file and then populate it in my .c?

Something like

int arr[];
arr = {5, 2, 9, 8};

      

I'm new to C, not sure how this would look like

any suggestions?

+2


a source to share


2 answers


Typically you add:

extern int arr[];

      

In the .h file and:



int arr[] = { 5, 2, 9, 8};

      

In the .c file.

Edit: Dale Hagglund and KevinDTimm bring up the good points: you want to put the initialization in one .c file, and you only need to put anything in the .h file if you're going to access arr

from code in more than one .c file.

+9


a source


You can use included guards to prevent inadvertent assignment of assignemnt, but including assignment in headers is very bad practice in my opinion. Place the initialization in file c, in the init function and replace the array in file h.



0


a source







All Articles