You are not logged in.

#1 2008-11-17 18:51:30

tony5429
Member
Registered: 2006-03-28
Posts: 1,017

Defining an Array in C

I'd like to define an array in my C programme above the main function and then call it like this...

#define x {4, 4.6, 5, 2.3}

int main() {
     double y;

     y = x[2];

     return 0;
}

But when I try to compile this, I get the error "error: expected expression befor '{' token." I don't even have a '{' token in the code. Can anyone help me? Thanks.

Offline

#2 2008-11-17 19:07:03

Mashi
Member
Registered: 2007-02-19
Posts: 38

Re: Defining an Array in C

You do have a "{", you're using it for the boundaries of your array.

I'm no C guru but I think what you want to do is something like this:

double x[] = {4, 4.6, 5, 2.3}

int main() {
    double y = x[2];
    // etc
}

Last edited by Mashi (2008-11-17 19:07:37)

Offline

#3 2008-11-17 19:18:38

Cerebral
Forum Fellow
From: Waterloo, ON, CA
Registered: 2005-04-08
Posts: 3,108
Website

Re: Defining an Array in C

Stay away from #define for things like this - #define is a preprocessor macro and really shouldn't be used for this purpose.

Mashi is correct, if you want a constant array, define it like so:

const double x[] = {4, 4.6, 5, 2.3};

int main() {
    double y = x[2];
    // etc
}

-edit- A good source for information on preprocessor directives would be http://www.cplusplus.com/doc/tutorial/preprocessor.html - it's a C++ information site, but the info is pretty well the same for C/C++, as they use very similar preprocessors. -/edit-

Last edited by Cerebral (2008-11-17 19:25:59)

Offline

#4 2008-11-17 19:44:51

xen
Member
Registered: 2008-08-17
Posts: 56

Re: Defining an Array in C

I know its possible to learn a programming language from entirely free resources, but I would highly recommend picking up a copy of this book: http://www.amazon.com/Programming-Langu … 018&sr=8-1

I found it to be a very concise guide to using the language and has a permanent place in my technical library smile


A wannabe game-developer.
My Blog
My GitHub

Offline

#5 2008-11-17 20:00:24

string
Member
Registered: 2008-11-03
Posts: 286

Re: Defining an Array in C

If you really want to do it:

#define X {4, 4.6, 5, 2.3}

int main(void)
{
    double x[] = X;
    double y;

    y = x[2];
    return 0;
}

Offline

#6 2008-11-17 22:51:09

tony5429
Member
Registered: 2006-03-28
Posts: 1,017

Re: Defining an Array in C

Thanks guys. I tried Cerebral's code and it works fine.

Offline

Board footer

Powered by FluxBB