C language - three methods to output all elements in an array

Table of contents

Define an array, fill it with data, and output all elements in the array:

Method 1: subscript method

Method 2: Calculate the element address through the array name to output:

Method 3: Use pointers to output


Define an array, fill it with data, and output all elements in the array:

Method 1: subscript method

#include<stdio.h>
int main()
{
    int ar[5] = {1,2,3,4,5};
    for(int i = 0;i < 5;i++){ 
        printf("%3d",ar[i]);
    }
    return 0;
}

operation result:

 

output complete 

Method 2: Calculate the element address through the array name to output:

#include<stdio.h>
int main()
{
    int ar[5] = {1,2,3,4,5};
    int *p = ar;//数组名代表数组首元素地址
    for(int i=0;i<5;i++){
        printf("%d",*p+i);
    }
    return 0;
}

operation result:

Method 3: Use pointers to output

#include<stdio.h>
int main()
{
    int i;
    int data[10] = {1,2,3,4,5};//定义数组
    int *p;
    for(p = data;p<(data+5);p++){
        printf("%d",*p);
    }
    return 0;
}

As shown in the figure is the running result:

Guess you like

Origin blog.csdn.net/weixin_45571585/article/details/124885884
Recommended