-
array questions
I have the following simplified code.
Code:
void TestChannels(int *Chan) {
int x;
for (x=0; x<9; x++) {
Chan[x] = x * 2; // Problem is here
}
}
int main() {
int Channel[9];
int x;
//Initialization
for (x=0; x<9; x++) {
Channel[x] = 0;
}
TestChannels(Channel);
for (x=0; x<9; x++) {
printf("Channel %d = %d", x, Channel[x]);
}
}
My question is, within the function, how do I refer to the individual elements of Channel?
-
And what is wrong with the code as you have it?
--
Mats
-
Your use of Chan[x] is correct. However, I suggest adding a parameter for the size of the array to the TestChannels function.
Note that if you want to do zero initialisation of the array, this would suffice:
Code:
int Channel[9] = {0};
You can then dispense with the loop that sets each element of Channel to 0.
-
If you expected this:
Channel 0 = 0Channel 1 = 2Channel 2 = 4Channel 3 = 6Channel 4 = 8Channel 5 = 10Channel 6 = 12Channel 7 = 14Channel 8 = 16
Then I don't understand how you are having a problem; there is nothing wrong with your code. One tip, tho: you can initialize all the elements to zero this way:
Code:
int Channel[9]={0};
Which it's not particularly necessary in your code anyway, since the entire array gets written into by TestChannels().
[edit] you know what they say about great minds.
-
Hmmm... Well nothing is wrong... I simplified the actual code I had that wasn't working... I will analyze and get back...
and thanks for the intialization tip
-
What about this... this is more how my original was structured...
Code:
void VerifyChannels(int *Chan) {
int x;
for (x=0; x<9; x++) {
Chan[x] = x * 2; // Problem is here
}
}
void TestChannels(int *Chan) {
VerifyChannels(&Chan);
}
int main() {
int Channel[9];
int x;
//Initialization
for (x=0; x<9; x++) {
Channel[x] = 0;
}
TestChannels(Channel);
for (x=0; x<9; x++) {
printf("Channel %d = %d", x, Channel[x]);
}
}
My error was the & in VerifyChannels(&Chan); It should not have been there.
-
Code:
void TestChannels(int *Chan) {
VerifyChannels(&Chan);
}
This should AT LEAST give you a warning for incompatible pointer types.
--
Mats