当前位置:网站首页>Pointer and array are input in function to realize reverse order output

Pointer and array are input in function to realize reverse order output

2022-07-07 04:55:00 Xiaohao programming

Input what output what

#include <stdio.h>
void initarray(int *parr,int size)
{
    
    int i;
    for(i=0;i<size;i++)
    {
    
        printf(" Please enter the first %d Data of elements :\n",i+1);
        scanf("%d",parr++);//parr That's the address ( The pointer ), You don't have to take the address anymore 
    }
}
void printarray(int *parr,int size)
{
    
    int i;
    for(i=0;i<size;i++)
    {
    
        printf("%d ",*parr++);// Address ( The pointer ) Value , Type it out 
    }
}

int main()
{
    
    int arry[5];
    int size = sizeof(arry)/sizeof(arry[0]);
    initarray(arry,size);//arry  The array name is the array address 、 First element address 
    printarray(&arry[0],size);//&arry[0] The address of the first element is the same as the above 
    return 0;
}

Output results
 Insert picture description here

Reverse input and output

#include <stdio.h>
void initarray(int *parr,int size)
{
    
    int i;
    for(i=0;i<size;i++)
    {
    
        printf(" Please enter the first %d Data of elements :\n",i+1);
        scanf("%d",parr++);//parr That's the address ( The pointer ), You don't have to take the address anymore 
    }
}

/* void revangearry(int *parr,int size)// Output the input data in reverse order  { int i,j; int tmp; for(i=0;i<size/2;i++) { j = size-1-i; tmp = parr[i]; parr[i] = parr[j]; parr[j] = tmp; } } */
// The above function is written in another way , Closer to the writing of pointer 
void revangearry(int *parr,int size)// Output the input data in reverse order 
{
    
    int i,j;
    int tmp;
    for(i=0;i<size/2;i++)
    {
    
        j = size-1-i;
        tmp = *(parr+i);// The array address is offset directly according to the array type , It also has the same effect as the above 
        *(parr+i) = *(parr+j);// Address offset according to array type , The value was changed at the corresponding address 
        *(parr+j) = tmp;
    }
}

void printarray(int *parr,int size)
{
    
    int i;
    for(i=0;i<size;i++)
    {
    
        printf("%d ",*parr++);// Address ( The pointer ) Value , Type it out 
    }
}

int main()
{
    
    int arry[5];
    int size = sizeof(arry)/sizeof(arry[0]);
    initarray(arry,size);//arry  The array name is the array address 、 First element address 
    revangearry(arry,size);// In reverse order 
    printarray(&arry[0],size);//&arry[0] The address of the first element is the same as the above 
    return 0;
}

Output results
 Insert picture description here

原网站

版权声明
本文为[Xiaohao programming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207062221372869.html