I'm a complete c newb. I'm trying to define a few functions in a header file and then implement them in a separate file. But when I try running gcc runtime.c
I get the following error:
In file included from runtime.c:1:
runtime.h:7: error: expected identifier or ‘(’ before ‘[’ token
Here's the contents of runtime.h:
#ifndef HEADER
#define HEADER
/*given two arrays of ints, add them
*/
int[] * _addInts(int[] *x, int[] *y);
#endif
What's the er开发者_如何学Pythonror? I tried browsing header files but they started adding things like "extern" and "intern" and crazy ifdef's. Thanks for your help, Kevin
You should just pass pointers (since if you pass arrays to a function, what;'s really passed is a pointer anyway). Also, you can't return an array - again, just return a pointer:
int* _addInts(int *x, int *y); // equivalent to: int* _addInts(int x[], int y[]);
You'll also have to arrange for the number of elements to be passed in somehow. Something like the following might work for you:
int* _addInts(int *x, int *y, size_t count);
Also - do not fall into the trap of trying to use sizeof
on array parameters, since they're really pointers in C:
int* _addInts(int x[], int y[])
{
// the following will always print the size of a pointer (probably
// 4 or 8):
printf( "sizeof x: %u, sizeof y: %u\n", sizeof(x), sizeof(y));
}
That's one reason why I'd prefer having the parameters be declared as pointers rather than arrays - because they really will be pointers.
See Is there a standard function in C that would return the length of an array? for a macro that will return the number of elements in an array for actual arrays and will cause a compiler error (on most compilers) much of the time when you try to use it on pointers.
If your compiler is GCC, you can use Linux's trick: Equivalents to MSVC's _countof in other compilers?
Get rid of each "[]"
As an array is a pointer, you only need to pass the pointers, like so:
int* _addInts(int* x, int* y);
EDIT: Also pass the size.
Use:
int* addInts(int* x, int* y, int size);
You have the [] in the wrong locations. The syntax for declaring arrays in "C" has the [] coming after the item you want to be an array, not between the type declaration and the item (like Java and C# use). I am not sure what you are trying to declare, but here are some options:
If you are trying to declare that you will be using a function named "_addInts()" that returns a pointer to an int, and takes as its parameters two separate arrays of pointers to integers named x and y --
int * _addInts(int *x[], int *y[]);
If you want to declare a function that returns an array of integer pointers:
int * _addInts(int *x[], int *y[])[];
If _addInts is a function that takes two arrays of int (as opposed to arrays of int *):
int * _addInts(int x[], int y[]);
Note that the following are (nearly) equivalent, and can be used interchangeably in declarations such as you are attempting.
int *x
and
int x[]
as are:
int **x
and
int *x[]
精彩评论