开发者

Predefining C Array

开发者 https://www.devze.com 2022-12-28 06:25 出处:网络
In C, when defining an array I c开发者_如何学Goan 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

In C, when defining an array I c开发者_如何学Goan 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?


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.


You can use include guards to prevent the assignemnt from happening multiple times, but putting the assignment into headers is a very bad practice in my opinion. Put the intialization in a c file, in an init function instead and extern the array in the h file.

0

精彩评论

暂无评论...
验证码 换一张
取 消