Qbasicnews.com

Full Version: C arrays -- 0 or 1 based?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Haven't been around for a while, but I was wondering if someone could quickly let me know what the syntax is for setting the base of an array in C++?

ie,
DIM myarray(5) 'has 6 elements 0..5
DIM myarray(1 TO 5) 'has 5 elements 1..5

in C,
int myarray[5] //appears to only have 5, but there's no range checking, so I'm not sure.
int mymultidimensionalarray[5][6] // how many here?
count starts on 0, well at least for perl. perl and c are a like so im guessing count on 0
Code:
int array[5];
int twoByTwo[5][6];

The first array has 5 elements {0, 1, 2, 3, 4}, the second is a 5 by 6 two dimensional array. In C array indexing begins at 0 and goes to n - 1, where n is the defined size of the array. Unfortunately C doesn't do bounds checking, so if you index an array outside of its bounds you may get garbage, you may get something slightly sensible or you may get a crash.
Just to add a couple thoughts to loose caboose's post...

array[5]

contains 5 elements, indexed 0-4. The 0-indexing can screw you up if you do not pay attention (which I know you do !! Big Grin )

a typical way of dealing with the zero-indexing (in c++, not c) is to use the "less than ubound" condition as follows.:

Code:
#include<iostream>

using namespace std;

int main(){
   int elements = 5;
   int array[5];  //5 element array, filled with ????
   for(int i = 0; i < elements; ++i)
     cout << array[i] << endl;
   return 0;
}

or...you can use vectors:

Code:
#include<vector>
#include<iostream>

using namespace std;

int main(){
   vector<int>array(5);  //5 element array, filled with zeros
   for(int i = 0; i < array.size(); ++i)
     cout << array[i] << endl;
   return 0;
}
Quote:myClass* mypointer
mypointer = new myClass
myClass* myotherpointer
myotherpointer = mypointer // Error here ('Can't use mypointer as a function')

Disregard this. It was me being retarded and mixing up languages again. I was referring to my array of class pointers with parenthesis instead of square brackets.