Three forms of assigning values to arrays in C language

angryTom
Release: 2020-03-09 14:02:11
Original
13812 people have browsed it

Three forms of assigning values ​​to arrays in C language

Three forms of assignment to arrays in C language

In C language, three forms of assignment to arrays

Recommended learning:C language video tutorial

1. Through the form of loop, that is: array name [subscript], assign values to the elements of the array in sequence

#include  int main() { int i; int a[10] = {0}; for(i=0;i<10;i++) { scanf("%d",&a[i]); } for(i=0;i<10;i++) { printf("%d ",a[i]); } return 0; }
Copy after login

2. Assign values to the elements of the array in sequence through the form of a loop Array name subscript

#include  int main() { int i; int a[5]; // 数组名:a 是数组首元素的地址 -----相当于一个指针 是一个常量 //指针+整型值,表示地址的前移,前移的字节由指针指向的对象的类型决定 //b+1; 前移4个字节(int型) printf("%#p\n",a); //打印输出数组a的地址 相当于a[0]的地址 printf("%#p\n",&a[0]); printf("%#p\n",a+1); printf("%#p\n",&a[1]); printf("%#p\n",a+2); printf("%#p\n",&a[2]); printf("请输入数组a元素的值:"); for(i=0;i<5;i++) { scanf("%d",a+i); //赋值给数组a } printf("a数组元素的值为:"); for(i=0;i<5;i++) { printf("%d ",*(a+i)); } return 0; }
Copy after login

The printed result:

Three forms of assigning values ​​to arrays in C language

3. Use pointers to assign values to the elements of the array in sequence through loops

#include  int main() { int i; int d[5] = {10,20,34,89,90}; //指针指向一维数组,指针指向数组首元素 //数据类型 *指针名; int *p = d; //int *p = &d[0]; //指针指向数组首元素。指针名可以当数组名使用 printf("%#p\n",p); printf("%d\n",d[0]); printf("%d\n",*++p); //++p p的地址先偏移, *p printf("%d\n",d[1]); printf("%#p\n",p); printf("%#p\n",&d[1]); printf("请输入数组d元素的值:"); p = d; for(i = 0; i < 5; i++) { //scanf("%d",p+i); //p+0 p+1 p+2 p+3 scanf("%d",p++); //p = p+1 } //for循环结束,p偏移到元素d[4]的下一个元素 p = &d[0]; for(i = 0; i < 5; i++) { //printf("%d ",*(p+i)); //printf("%d ",*p++); //p++,后置 *p取p变化之前的内容 printf("%d ",p[i]); //指针指向数组首元素。指针名可以当数组名使用 } printf("\n-----------------\n"); return 0; }
Copy after login

For more C language relatedProgramming introductory tutorials, please pay attention PHP Chinese website!

The above is the detailed content of Three forms of assigning values to arrays in C language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!