Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Predefining C Array

Tags:

arrays

c

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

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

And thus I defined it and filled it up, but how do I define it in my .h file, and then fill it in my .c?

Like do something like

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

I'm pretty new to C, not sure how it would look

any suggestions?

like image 748
Johannes Jensen Avatar asked Feb 15 '26 14:02

Johannes Jensen


1 Answers

Normally, you'd put:

extern int arr[];

In the .h file, and:

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

In the .c file.

Edit: Dale Hagglund and KevinDTimm raise good points: you only 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.

like image 182
Jerry Coffin Avatar answered Feb 18 '26 04:02

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!