开发者

declaring an array of pointers in a C header file and assigning value?

Is it possible to declare an array of pointers and later on initialize either of them开发者_如何学编程 and assign a value, in a C header file?

char *i[2];  
i[0] = "abc";

the following does not work.

char *x = "def"; // this will, of course.

How am I supposed to declare and assign values for an array of pointers?


This has nothing to do with header files. You cannot create a .c file and put in it code like this:

char *i[2];  
i[0] = "abc";

In C, all code except definitions and initialisations must be inside functions, and your second statement is neither of these - it is an assignment.

An initialisation for your array would look like this:

char *i[2] = {"foo","bar"};

And that could be put in a header file, but would cause multiple definition errors if the header were used in more than one translation unit.


It's technically possible. But you should never declare variables on header files. Do it on .c files.

Also, you should initialize char * vectors with something like this:

char *i[2] = { "ABC", "CDE" };


Is this what you're looking for?

char *i[2] = {"abc", "def"};

Though it'll give you a warning unless you make them const char *

const char *i[2] = {"abc", "def"};


Are you sure your code

char *i[2];  
i[0] = "abc";

doesn't works?? could you post the errors?

I tried this in gcc and vc++ and it works just fine.

You can also go through the tutorial at this link: http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.4.html

Excerpts:

char * nameptr[MAX];

The array, nameptr[], is an array of size MAX, and each element of the array is a character pointer. It is then possible to assign character pointer values to the elements of the array; for example:

nameptr[i] = "John Smith";

The string "John Smith" is placed somewhere in memory by the compiler and the pointer to the string constant is then assigned to nameptr[i].

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜