学点 C 语言(21): 数据类型 - 数组与指针
获取数组的地址无须 &, 因为数组名本身就是个地址
include <stdio.h>
int main(void)
{
char c = 'A';
char cs[] = "ABC";
printf("%c, %s\n", c, cs); /* 获取字符及字符数组的内容 */
printf("%p, %p, %p\n", &c, cs, &cs); /* 获取字符及字符数组的地址, cs 与 &cs 没有区别*/
getchar();
return 0;
}
数组元素的地址是连续的:
include <stdio.h>
int main(void)
{
char cs[] = "ABC";
printf("%p\n%p\n%p\n%p\n", cs, &cs[0], &cs[1], &cs[2]);
getchar();
return 0;
}
数组名所代表的地址就是第一个元素的地址:
include <stdio.h>
int main(void)
{
char str[] = "ABC";
char *p1 = str;
char *p2 = &str[0];
printf("%p, %p\n", p1, p2);
getchar();
return 0;
}
通过指针访问数组元素:
include <stdio.h>
int main(void)
{
char str[] = "ABC";
char *p = str;
printf("%c\n", *p);
printf("%c\n", *p+1);
printf("%c\n", *p+2);
printf("\n");
printf("%c\n", *p);
printf("%c\n", *++p);
printf("%c\n", *++p);
getchar();
return 0;
}
通过指针遍历数组:
include <stdio.h>
int main(void)
{
char str[] = "123456789";
char *p = str;
int i;
for (i = 0; i < sizeof str/sizeof str[0]; i++) {
printf("%c\n", *p);
p++;
}
getchar();
return 0;
}
include <stdio.h>
int main(void)
{
char str[] = "123456789";
char *p = str;
while (*p != '\0') {
printf("%c\n", *p);
p++;
}
getchar();
return 0;
}
include <stdio.h>
include <string.h>
int main(void)
{
char str[] = "123456789";
char *p = str;
int i;
for (i = 0; i < strlen(str); i++) {
printf("%c\n", *(p+i));
}
getchar();
return 0;
}
include <stdio.h>
int main(void)
{
int nums[] = {111,222,333,444};
int *p = nums;
int i;
for (i = 0; i < sizeof nums / sizeof nums[0]; i++) {
printf("%d\n", *p++);
}
getchar();
return 0;
}
注意: 指针+1 是根据元素大小移动一个位置
include <stdio.h>
int main(void)
{
int nums[] = {111,222,333,444};
int *p = nums;
int i;
printf("%d\n", *p);
printf("%d\n", *(p+1));
printf("%d\n", *p+1); /* 不是这样; 这是代表取值后再 + 1 */
getchar();
return 0;
}
上面的指针其实都是数组元素的指针, 如何声明真正的数组指针呢?
include <stdio.h>
int main(void)
{
int nums[4] = {111,222,333,444};
int (*p)[4] = &nums; /* 注意其中的小括号 */
printf("%d\n", (*p)[1]); /* 用起来并不方便 */
printf("%d\n", (*p)[2]);
getchar();
return 0;
}
如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!
txttool.com 说一段 esp56物联 查询128 IP查询