欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言数组

程序员文章站 2024-03-15 12:32:29
...

1. 一维数组(1)

/*
============================================================================  
 Name        : Array.c  
 Author      : jiangkuan  
 Version     :  
 Copyright   : Your copyright notice  
 Description : Hello World in C, Ansi-style  
 ============================================================================  
 */  
  
#include <stdio.h>  
#include <stdlib.h>  
  
int main(void) {  
    int len = 10;  
    int arr[len];  
  
    for (int i = 0; i < len; i++) {  
        printf("index %d,and value is %d\n",i,arr[i]);  
    }  
    return EXIT_SUCCESS;  
}

运行结果:

C语言数组


2. 一维数组(2)

/*
 ============================================================================
 Name        : Array.c
 Author      : jiangkuan
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main(void) {
	int32_t len = 10;
	int32_t arr[len];

	int arr1[] = {1,2,5,7,3,8};

	for(int a = 0;a < len;a++){
		arr[a] = 0;
	}

	for (int32_t i = 0; i < len; i++) {
		printf("index %d,and value is %d\n",i,arr[i]);
	}

	for(int i = 0;i < 6;i++){
		printf("%d\n",arr1[i]);
	}
	return EXIT_SUCCESS;
}


运行结果:

C语言数组


3. 二维数组

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main(void) {

	int arr[3][4];
	int arr1[3][4] = {
			{1,2,3,4},
			{5,6,7,8},
			{9,10,11,12}
	};
	//clear arr
	for (int i = 0; i < 3; i++) {
		for(int j = 0;j < 4;j++){
			arr[i][j] = 0;
		}
	}

	for (int i = 0; i < 3; i++) {
		for(int j = 0;j < 4;j++){
			printf("index(%d,%d),%d\n",i,j,arr[i][j]);
		}
	}

	return EXIT_SUCCESS;
}

运行结果:

C语言数组


4. 字符串数组

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {

	char str[10] = {'H','e','\0','l','l','o','\0'};
	printf("string length is %ld ,and string is %s\n",strlen(str),str);

	memset(str,0,10);
	printf("string length is %ld ,and string is %s\n",strlen(str),str);

	char str1[] = "hello world";
	for(int i = 0;i < strlen(str1); i++){
		printf("[index:%d]%c\n",i,str1[i]);
	}
	printf(str1);

	return EXIT_SUCCESS;
}

运行结果:

C语言数组




相关标签: 数组