To define an integer or floating point variable you would say.
main() { int Count; /* integer variable */ float Miles; /* floating point variable */ }
The syntax for an array is:
main() { int Count[5]; /* 5 element integer array */ float Miles[10]; /* 10 element floating point array */ }
Now, the important fact is that the elements start at 0 (ZERO), so, 'Count' above has elements 0, 1, 2, 3, 4.
To change the value of the 5th element we would code:
main() { int Count[5]; Count[4] = 20; /* code 4 to update the 5th element */ }
If we want to initalise 'Count' at definition we can say:
main() { int i; int Count[5]={10, 20, 30}; for (i=0; i<5; i++) { printf("%d ", Count[i]); } puts(""); }The result will be:
10 20 30 0 0We can see from the example above that the elements that have NOT been initalised have been set to zero. One last thing to show you. If all the elements are being initialized when the variable is being defined, the compiler can work out the number of elements for you. So this example will create an array with 3 elements.
main() { int i; int Count[]={10, 20, 30}; }Don't forget, all the stuff so far also applies to float.
main() { int Count[5]; int Matrix[10][4]; }Count has been seen before, it defines an array of 5 elements. Matrix is defined as 10 arrays, all with 4 elements. To initalise Matrix at definition, you would code the following.
main() { int Matrix[4][2]={{1, 2}, {3, 4}, {5, 6}, {7, 8}}; }Dont forget the last element will be Matrix[3][1]
main() { char Letter; char Letters[10]; }'Letter' can only hold one character but 'the 'Letters' array could hold 10. It is important to think of 'char' as an array and NOT a string. To initalise 'char' variables you can use the following syntax.
main() { char Letter='x'; char Letters[10]='f','a','x',' ','m','o','d','e','m','\0'; char Text[10]="fax modem"; }Note that the double quotes mean 'text string' and so they will add the NULL automatically. This is the only time that text can be loaded into an array in this way. If you want to change the contents of the array you should use the function strcpy.
main() { char Colours[3][6]={"red","green","blue"}; printf ("%c \n", Colours[0][0]); /* O/P 'r' */ printf ("%s \n", Colours[1]); /* O/P 'green' */ }The example above has reserved 18 consecutive bytes and created three pointers into them.
--------------------- |red \0green\0blue \0| --------------------- A A A | | | Colours[0] ---- | | Colours[1] ----------- | Colours[2] ------------------
click here for chat on pointers.