将数组传递给函数时出现问题
由于某种原因,它似乎有一半的元素丢失了,并被其他一些东西所替代。
当我在调用方法之前迭代数组时,得到以下输出:
Votes: 2387
Votes: 2105
Votes: 1230
Votes: 1132
Votes: 2587
Votes: 559
在方法内部,我得到以下信息:
Votes: 2387
Votes: 1230
Votes: 2587
Votes: 1
Votes: 6689632
Votes: 4199349
看来它乘以2乘2而不是将1加到迭代器上,也许我没有以正确的方式使用指针。
这是代码,也许您可以看到问题所在:
#include<stdio.h>
#include<stdlib.h>
void method(int *options[], int *numberOfOptions);
main() {
int options[6] = {2387,2105,1230,1132,2587,559};
int size = 6;
int i = 0;
while (i < size) {
printf("Votes: %d \n",options[i]);
i++;
}
method (&options,&size);
}
void method(int *options[], int *numberOfOptions) {
int i = 0;
while (i < *numberOfOptions) {
int optionVotes = options[i];
printf("Votes: %d \n",optionVotes);
i++;
}
}
编译器会发出有关数组指针传递的警告。您也不必要将数组大小作为指针传递。
#include<stdio.h>
#include<stdlib.h>
void method(int *options, int numberOfOptions);
main() {
int options[6] = {2387,2105,1230,1132,2587,559};
int size = 6;
int i = 0;
while (i < size) {
printf("Votes: %d \n",options[i]);
i++;
}
method (options,size);
}
void method(int *options, int numberOfOptions) {
int i = 0;
while (i < numberOfOptions) {
int optionVotes = options[i];
printf("Votes: %d \n",optionVotes);
i++;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句