Home > Article > Backend Development > 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 <stdio.h> 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; }
2. Assign values to the elements of the array in sequence through the form of a loop Array name subscript
#include <stdio.h> 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; }
The printed result:
3. Use pointers to assign values to the elements of the array in sequence through loops
#include <stdio.h> 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; }
For more C language related Programming 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!