S1E22:指针和数组
本帖最后由 BaysideLizard 于 2023-11-14 22:22 编辑#include <stdio.h>
#include <string.h>
//DNX写于2023年10月5日
int main()
{
int a;
int *pa = &a;
printf("请输入整数a:");
scanf("%d",&a);//需要取址符
printf("a = %d\n请再次输入整数a:",a);
scanf("%d",pa);//存放的就是地址,不需要取址符。
printf("a = %d\n\n",a);
char b;
printf("请输入字符串b:");
scanf("%s",b);//数组名存放的是第一个元素的地址。
printf("b = %s\n",b);
printf("The address of b is %p\n",b);
printf("The address of b is %p\n\n",&b);
char h = "zzh";
int i = {1,2,3};
float j = {1.1,2.2,3.3};
double k = {1.11,2.22,3.33};
printf("char h -> %p,h -> %p, h -> %p\n",&h,&h,&h);
printf("int i -> %p,i -> %p, i -> %p\n",&i,&i,&i);
printf("flout j -> %p,j -> %p, j -> %p\n",&j,&j,&j);
printf("double k -> %p,k -> %p, k -> %p\n",&k,&k,&k);
//还可以用指针定义一个数组
char *str = "wasd";
int r, length;
length = strlen(str);
for (r = 0; r < length; r++) {
printf("%c", str);//用下标法读取元素
}
putchar('\n');
for (r = 0; r < length; r++) {
printf("%c", *(str+r));//用指针读取元素
}
putchar('\n');
return 0;
}
运行结果:
请输入整数a:1
a = 1
请再次输入整数a:2
a = 2
请输入字符串b:Hello!
b = Hello!
The address of b is 000000000062FD80
The address of b is 000000000062FD80
char h -> 000000000062FD70,h -> 000000000062FD71, h -> 000000000062FD72
int i -> 000000000062FD60,i -> 000000000062FD64, i -> 000000000062FD68
flout j -> 000000000062FD50,j -> 000000000062FD54, j -> 000000000062FD58
double k -> 000000000062FD30,k -> 000000000062FD38, k -> 000000000062FD40
wasd
wasd
--------------------------------
Process exited after 10.73 seconds with return value 0
请按任意键继续. . .
在FishC学C的第八天
加油! 坚持
页:
[1]