关于指针的一些问题
本帖最后由 HQWQF 于 2021-9-26 23:03 编辑#include<stdio.h>
intmain()
{
int(*str)[] = {"123456"};
printf("%p\n", str);
#include<stdio.h>
intmain()
{
int(*str)[] = {"123456"};
printf("%p\n", *str);
1.这两段代码的输出分别代表什么?而且打印的结果会变化,是不是访问了未初始化的指针?
2另外,如果像这样把两种打印放到同一段代码中,两种输出就一致了,为什么?
#include<stdio.h>
intmain()
{
int(*str)[] = {"123456"};
printf("%p\n", *str);
printf("%p\n", str);
}
3.为什么这样的代码会报错,上面的就不会(用的vs2019)?
#include<stdio.h>
intmain()
{
int(*str) = {1,2,3,4};
} 本帖最后由 人造人 于 2021-9-26 23:36 编辑
#include <stdio.h>
int main(void) {
int array[] = {1, 2, 3};
int (*p)[] = &array;
printf("%p\n", p);
printf("%p\n", &array);
printf("%p\n", *p);
printf("%p\n", *&array);
printf("%p\n", array);
printf("%p\n", &array);
int (*a)[];
a = p;
a = &array;
printf("%p\n", a);
int *b;
b = *p;
b = *&array;
b = array;
b = &array;
printf("%p\n", b);
return 0;
}
#include <stdio.h>
int main(void) {
int (*str)[] = {"123456"};
printf("%p\n", str);
return 0;
}
这个代码会有警告
$ gcc -g -Wall -o main main.c
main.c: In function ‘main’:
main.c:4:21: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
int (*str)[] = {"123456"};
^~~~~~~~
main.c:4:21: note: (near initialization for ‘str’)
$
等于号左边是一个指针,右边是一个初始化列表
#include <stdio.h>
int main(void) {
int (*str)[] = &(int *[]){"123456"};
printf("%p\n", str);
return 0;
}
改成这样还是有警告
$ gcc -g -Wall -o main main.c
main.c: In function ‘main’:
main.c:4:31: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
int (*str)[] = &(int *[]){"123456"};
^~~~~~~~
main.c:4:31: note: (near initialization for ‘(anonymous)’)
main.c:4:20: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
int (*str)[] = &(int *[]){"123456"};
^
$
因为初始化列表中的是一个字符串,应该是下面这样的
#include <stdio.h>
int main(void) {
const char *(*str)[] = &(const char *[]){"123456"};
printf("%p\n", str);
return 0;
}
$ gcc -g -Wall -o main main.c
$
页:
[1]