gpt4 book ai didi

c - 仅使用指针来打印数组的内容

转载 作者:行者123 更新时间:2023-11-30 15:09:33 24 4
gpt4 key购买 nike

我被要求编写一个函数,在第 x 个元素之后打印数组的内容(如 x 等,如 x 是数组内的指针)。除了初始化之外,我不允许使用 [] 进行任何其他操作,并且不允许在函数内部创建变量 - 我只能使用函数从 main 接收的内容,即长度 (int n)、数组 (int* arr) 和元素 x (int* x)。

我的问题是如何仅使用没有循环索引的指针在数组中打印 x 以及来回?

这是我写的:

void printAfterX(int* arr, int n, int* x)
{
if ((arr <= x) && (x < arr + n))
{
while(x < (arr + n))
{
printf("%8d", *(arr+x)); //I know you can't do this
x++;
}
}
}

为此:

    int arr[] = { 0,5,6,7,8,4,3,6,1,2 };
int n=10;
int* x = (arr+3);

printAfterX(arr, n, x);

输出应该是:

7 8 4 3 6 1 2

编辑:谢谢大家的帮助!效果很好。 :)

最佳答案

void printAfterX(int* arr, int n, int* x)
{
arr += n; // make arr to point past the last element of the array
for( ; x < arr; x++) // walk till the end of array
printf("%8d", *x); // print the current item
}

示例 https://ideone.com/Ea3ceT

关于c - 仅使用指针来打印数组的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36615890/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com