Arrays

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
Arrow

Arrays

Post by Arrow »

When I do something like this in a method:
int a = 2;
if(variabel == a) {
...
}

it works, but Not when using arrays like this:
int *a = {1,2,3};
if(variabel == a[1]) {
.....
}
it just doesnt work in any way...anything special I need to know about arrays??
HOS

Re:Arrays

Post by HOS »

Arrow wrote: int *a = {1,2,3};
if you dont need to change the array you should be able to do something like

Code: Select all

int a[] = {1,2,3};
that worked for me, but i had compile errors using your syntax. another thing to remember is that arrays are 0-indexed
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re:Arrays

Post by Solar »

Arrow wrote: int *a = {1,2,3};
if(variabel == a[1]) {
.....
}
int *a is not an array of integers, but a pointer to one integer. Your compiler should give you at least a warning about this; GCC sure does.

Correct is:

Code: Select all

int a[] = {1,2,3};
It is correct that syntactically, "a" can be handled as a pointer-to-int (as in, e.g. *a+5, but you have to declare it correctly so the compiler knows what you're intending.
Every good solution is obvious once you've found it.
Post Reply