Reputation: 3
I have been asked to write a function that prints the content of an array after the x
th element (as in, x
and forth, as x
is a pointer inside the array). I am not allowed to use []
for anything other than initialization, and not allowed to create variables inside the function - I may only use what the function receives from the main, which is the length (int n
), the array (int* arr
) and element x
(int* x
).
My question is how can I print x
and forth in the array using only pointers without an index from a loop?
Here is what I wrote:
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++;
}
}
}
For this:
int arr[] = { 0,5,6,7,8,4,3,6,1,2 };
int n=10;
int* x = (arr+3);
printAfterX(arr, n, x);
The output should be:
7 8 4 3 6 1 2
Edit: Thanks y'all for the help! Works just fine. :)
Upvotes: 0
Views: 238
Reputation: 50778
You want this:
#include <stdio.h>
#include <stdlib.h>
void printAfterX(int* arr, int n, int* x)
{
while(x < (arr + n))
{
printf("%d ", *x);
x++;
}
}
int main()
{
int arr[] = { 0,5,6,7,8,4,3,6,1,2 };
int n = 10;
int *x = (arr+3);
printAfterX(arr, n, x);
return 0;
}
Upvotes: 0
Reputation: 9571
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
}
Example https://ideone.com/Ea3ceT
Upvotes: 2