c++ - 使用指针变量打印特定的数组变量

标签 c++ arrays function loops pointers

我是一名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);
}

请注意,

关于c++ - 使用指针变量打印特定的数组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57600342/

相关文章:

c++ - ON_NOTIFY、ON_CONTROL、ON_CONTROL_REFLECT 之间有什么区别?

c++ - 重写 if 语句,使其更简洁、更简洁

arrays - 无法在强制转换中将类型 [Struct] 的值转换为类型 [string]

arrays - 最常见的数组元素

c++ - 更改不在 Qt 主线程上的监听端口

c++ - 需要代码在 Visual Studio C++ 中动态分配 >1gb 内存数组

ruby - 排序:在 Ruby 中根据多个条件对数组进行排序

c - 将结构指针发送到 C 中的函数

python - 我如何在Python中循环函数变量?

Python:函数执行后不保存变量的值