我是一名C++初学者,我的任务如下:
Define and initialise a single-dimensional integer array. Next, define a pointer that points to the first element in the array and passes the pointer to a function.
Using only pointer variables (and looping constructs), print only the array values that are exact multiples of
7
from start to finish to standard output. The only program output should be the numbers, one per line with no white space.
我试过:
void print_sevens(int* nums, int length)
{
int array[5] = { 5,8,21,43,70 };
int* ptr = array;
int* num = array;
for (int i = 0; i < length; i++)
{
*num++;
if (num[i] % 7 == 0) {
cout << num[i] << endl;
}
}
}
int main()
{
int array[5] = { 5,8,21,43,70 };
int* ptr = array;
print_sevens(ptr, 5);
}
它编译但不输出任何东西。
我也对将指针传递给函数感到困惑。应该在主文件中还是在函数文件中完成?
最佳答案
您正在 print_sevens
函数中创建一个额外的数组,这是不必要的,因为您已经将指针传递给在 main()
中创建的数组的第一个元素(即 array
)。
把函数中那些不必要的array
和相关代码去掉,程序就可以完美运行了。 ( See online )
void print_sevens(int* nums, int length)
{
for (int i = 0; i < length; i++)
{
if (nums[i] % 7 == 0)
std::cout << nums[i] << std::endl;
}
}
在 main
中,您只需执行以下操作,如 arrays decay to the pointer pointing to its first element .
int main()
{
int array[5]{ 5,8,21,43,70 };
print_sevens(array, 5);
}
请注意,
num++
递增指针,而不是它所在的下划线元素 指向(由于operator++
的 operator precedence 高于operator*
)。如果你打算增加元素(pointee)你 应该有(*num)++
。- 其次,不要练习
using namespace std;
。阅读更多: Why is "using namespace std;" considered bad practice?
关于c++ - 使用指针变量打印特定的数组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57600342/