分别采用逐个赋值和字符串赋值两种方式对字符数组ch1 6赋值输出其字符值以及ascii值
时间: 2024-03-15 18:47:36 浏览: 97
以下是逐个赋值方式的示例代码:
```
#include <stdio.h>
int main() {
char ch1[6];
ch1[0] = 'H';
ch1[1] = 'e';
ch1[2] = 'l';
ch1[3] = 'l';
ch1[4] = 'o';
ch1[5] = '\0';
for(int i=0; i<6; i++) {
printf("ch1[%d] = %c, ASCII value = %d\n", i, ch1[i], ch1[i]);
}
return 0;
}
```
输出结果:
```
ch1[0] = H, ASCII value = 72
ch1[1] = e, ASCII value = 101
ch1[2] = l, ASCII value = 108
ch1[3] = l, ASCII value = 108
ch1[4] = o, ASCII value = 111
ch1[5] = , ASCII value = 0
```
以下是字符串赋值方式的示例代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char ch1[6];
strcpy(ch1, "Hello");
for(int i=0; i<6; i++) {
printf("ch1[%d] = %c, ASCII value = %d\n", i, ch1[i], ch1[i]);
}
return 0;
}
```
输出结果:
```
ch1[0] = H, ASCII value = 72
ch1[1] = e, ASCII value = 101
ch1[2] = l, ASCII value = 108
ch1[3] = l, ASCII value = 108
ch1[4] = o, ASCII value = 111
ch1[5] = , ASCII value = 0
```
可以看到,无论采用哪种方式赋值,输出的结果都是相同的。
阅读全文