char un 数组printf_[习题11]数组和字符串:char *test = "Hello world!"; printf("%s\n", test);...

"这篇博客探讨了C语言中数组和字符串的初始化和打印。通过示例代码展示了如何初始化整型数组和字符数组,以及如何使用printf函数进行输出。文中提到了未初始化数组元素的默认值为0,以及字符数组中''作为字符串结束符的重要性。还对比了直接赋值和使用指针访问字符串的差异,并提供了Makefile用于编译和运行程序。"
摘要由CSDN通过智能技术生成

使用教材

ex11.c

#include

int main(int argc,char *argv[])

{

int numbers[4] = {0};

char name[4] = {'a'};

//first, print them out raw

printf("numbers: %d %d %d %d\n", numbers[0], numbers[1], numbers[2], numbers[3]);

printf("name each: %c %c %c %c\n", name[0], name[1], name[2], name[3]);

printf("name: %s\n", name);

// set up the numbers

numbers[0] = 1;

numbers[1] = 2;

numbers[2] = 3;

numbers[3] = 4;

// set up the name

name[0] = 'Z';

name[1] = 'e';

name[2] = 'd';

name[3] = '\0';

// then print them out initialized

printf("numbers: %d %d %d %d\n", numbers[0], numbers[1], numbers[2], numbers[3]);

printf("name each: %c %c %c %c\n", name[0], name[1], name[2], name[3]);

// print the name link a string

printf("name: %s\n", name);

// another way for use name

char *another = "Zed";

printf("another: %s\n", another);

printf("another each: %c %c %c %c \n", another[0], another[1], another[2], another[3]);

return 0;

}

Makefile

CC=clang

CFLAGS=-Wall -g

clean:

rm -f ex11

run

anno@anno-m:~/Documents/mycode/ex11$ make ex11

clang -Wall -g ex11.c -o ex11

anno@anno-m:~/Documents/mycode/ex11$ ./ex11

numbers: 0 0 0 0

name each: a

name: a

numbers: 1 2 3 4

name each: Z e d

name: Zed

another: Zed

another each: Z e d

说明

数组如果只初始化了一个元素,剩下的元素会用0来填充;

int numbers[4] = {0};

numbers: 0 0 0 0

第1个0 是初始化的那个元素

剩余3个0是填充的0

char name[4] = {'a'};

name each: a

填充字符'\0'使得字符串被正确地结束了

初始化字符串 以及 输出字符串

char *another = "Zed";

printf("another: %s\n", another);

another: Zed

to-do

code

//to-do-1

int test_num[3] = {'0'};

test_num[0] = 'a';

printf("number %%d : %d\n", test_num[0]);

printf("number %%c : %c\n", test_num[0]);

//to-do-2

char test_name[3] = {};

test_name[0] = 't';

printf("char %%d : %d\n", test_name[0]);

//to-do-3

char *test_another = "Hello world!";

printf("%s\n", test_another);

output

number %d : 97

number %c : a

char %d : 116

Hello world!

C语言中字符char就是一个小整数,%d输出这个整数的值,%c输出这个字符;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值