with respect to pointers and sequences

Asked 2 years ago, Updated 2 years ago, 40 views

I don't know how to solve Kyoto Sangyo University's report problem.
Kyoto Sangyo University reporting assignment
I'm a high school student.
I'm learning the pointer.
I'm solving an exercise question on the Internet, but I don't know what to do with it.
Is it possible to complete this program without using b in the while statement?
What kind of code would you like to use?

#include<stdio.h>

int main()
{
 inta[10] = {1,2,3,4,5,6,7,8,9,10};
 intb[10];
 int*p, *q;
 inti;

 p = ???;
 q = ???;

 while(??? here we use p and a) {
     ???;
     ???; We use p and q here.
     ???;
 }

 for(i=0;i<10;i++){
     printf("%d",b[i]);
 }

 return 0;
}

Execution Example
10 9 8 7 6 5 4 3 2 1

c

2022-09-30 16:34

2 Answers

Perhaps the expected answers are as follows.
I also study pointer regularly, so I solved it while trying my skills.

int main(void){
    inta[10] = {1,2,3,4,5,6,7,8,9,10};
    intb[10];
    int*p, *q;
    inti;
    p=a+10;//orp=&a[10]
    q=b;//orp=&b[0]
    while(p!=a){
        p--;
        *q = *p;
        q++;
    }
    for(i=0;i<10;i++){
        printf("%d",b[i]);
    }
    scanf("%d\n", & a);
    return 0;
}

How to think
An array (a) is required to be stored in an array (b) in reverse order.
In order to do this, it is necessary to refer to the pointer b outside the while statement.(Otherwise, b cannot be changed by a given constraint.)
In C, a indicates a memory address & a[0] of a[0].
An addition a+10 to an address a indicates a memory address & a[10] of a[10].Therefore, it may be easier to understand how to write in the comment line.
Note that a+10 refers to an uninitialized memory address, inta[10]=...; initializes from a[0] to a[9] and you don't know what a[10] contains.Therefore, you must first do p--; in the while statement to avoid accessing a[10].
A value stored by a is accessed through a pointer of p in *q=*p; (also called deref or reference peeling) and stored in b through a pointer of q.
You may understand that adding and subtracting pointers p only shifts the address by the size of the pointer type, but I will check again.
For example, if p contains 00FF08, p is an int type (4-bit) pointer, so p-- is 00FF04 and p++ is 00FF0C.


2022-09-30 16:34

Outside the while statement

p=??;
q = ???;

is present in the while statement.

??; Use p and q here

You can predict that you will copy the value using p and q.

p, q point to the array of a, b, respectively, and copy p, q as they move from place to place.

Attempted to fill in ??.

#include<stdio.h>

int main()
{
    inta[10] = {1,2,3,4,5,6,7,8,9,10};
    intb[10];
    int*p, *q;
    inti;

    p = a;
    q = b + 10;

    while(p<a+10){
        q--;
        *q = *p;
        p++;
    }

    for(i=0;i<10;i++){
        printf("%d",b[i]);
    }

    return 0;
}


2022-09-30 16:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.