example1:已知行列,进行初始化
1.使用代码初始化二维数组 2.使用输入初始化二维数组 用malloc动态分配array内存实现1,使用静态实现2
#include <stdio.h>
#include <stdlib.h>
int main() {
int row, col, i, j;
int** array;
scanf("%d %d", &row, &col);
array = (int**)malloc(row * sizeof(int*));
for (i = 0; i < row; i++)
array[i] = (int*)malloc(col * sizeof(int));
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
array[i][j] = j+i;
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
printf("\n");
int arr[5][4];
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
scanf("%d", &arr[i][j]);
printf("\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
example2:输入字符串,将其中的数字分离出来
字符串长度固定。 将字符串中挨在一起的数字视为一个数字,输出出来,存入到数组当中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char s[100] = "\0";
char s1[100] = "\0";
int temp = 0;
int temp_cnt;
int flag = 0;
int strLen = 0;
int data_cnt = 0;
gets_s(s);
strLen = strlen(s);
int* data = (int*)malloc(sizeof(int) * strLen);
memset(data,'\0',strLen);
for (int i = 0; i < 100;) {
if (s[i] == '\0') {
break;
}
temp_cnt = 0;
while (s[i] >= '0' && s[i] <= '9') {
s1[temp_cnt] = s[i];
temp_cnt++;
i++;
flag = 1;
}
if (flag == 1) {
flag = 0;
temp = atoi(s1);
memset(s1, '\0', 10);
data[data_cnt] = temp;
printf("%d ", data[data_cnt]);
data_cnt++;
continue;
}
if (flag == 0) {
i++;
}
}
return 0;
}
结果如下
example3:scanf输入多个参数
输入的是坐标类型的数
[[5,4],[3,2],[7,8]]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char end; int val_x; int val_y; int flag = 0; int cnt = 1;
scanf("%c", &end);
scanf("%c", &end);
while (end == '[' || end == ']' || end == ',') {
if (end == '[') {
scanf("%d", &val_x);
scanf("%c", &end);
scanf("%d", &val_y);
printf("%d %d \n", val_x, val_y);
}
scanf("%c", &end);
if (end == ']') {
flag = 1;
scanf("%c", &end);
}
if (flag == 1) {
if (end == ']') { break; }
else { flag = 0; }
}
}
return 0;
}
|