c - 数组指针(在同一行中声明和定义给出垃圾值,而在不同行中工作得很好)

标签 c pointers

我正在使用 turbo c 当我不同地声明和定义指针 k 时,它会发出警告“不可移植指针转换”,* k 的结果显示为垃圾

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,*k;//declaration
int a[3][5] = {
{ 1, 2, 3, 4, 5 },
{6, 7, 8, 9, 10 },
{ 11, 12, 13, 14, 15 }
}; *k = &a ; //defination
clrscr();
printf("%d\n",*k);//garbage value
printf("%d\n",*(k+2));//garbage value
printf("%d\n",*(k+3)+1);//garbage value
printf("%d\n",*(k+5)+1);//garbage value
printf("%d\n",++*k);//garbage value
getch();
}

当在同一行中定义和声明指针 k 时,它给出了结果

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
int a[3][5] = {
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 14, 15 }
}, *k = &a ;
clrscr();
printf("%d\n",*k);         //1
printf("%d\n",*(k+2));     //3
printf("%d\n",*(k+3)+1);   //5
printf("%d\n",*(k+5)+1);   //7
printf("%d\n",++*k);       //2
getch();
}

此题取自《letusC》。

非常感谢您的回复!!

最佳答案

在第一个代码中,声明之后:

*k = &a ; //defination

导致未定义的行为,因为 k 未初始化,指向垃圾位置。

您应该将其更正为 k = *a;

而在第二个代码中,您在声明时分配地址。

首先,&a的类型是int(*)[3][5]a的类型是int (*)[5]*a 的类型是 int[5] 很容易衰减 int int*

其次,k的类型是int*(而*k类型是int)用于表达*k = &a 您可能会在这两个代码中收到警告。

分配二维数组中第一个元素的地址;检查以下内容:

第一个代码:

int *k;
int a[3][5] = {..........}; 
k = *a;

检查工作代码@ codepade

第二个代码:

int a[3][5] = {.........}, *k = *a;

检查工作代码@ codepade

要理解它,请阅读:

What does sizeof(&array) return?
What does the 'array name' mean in case of array of char pointers?

关于c - 数组指针(在同一行中声明和定义给出垃圾值,而在不同行中工作得很好),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19582187/

相关文章:

c - 为什么 printf 中的格式标记为 restrict?

在C中比较两个文件中的字符串;

c - 制作一个 usergiven_character*usergiven_repeatsinthestring(重复次数) 的字符串

c++ - 将新实例或其自身作为 std::shared_ptr 而不是原始指针返回

c++ - 指针声明

c++ - 指向 C 字符串的指针?

c - 向链表头部添加一个节点

c - 何时在 c、UART 函数中的函数参数中使用指针

c - C 中指针的奇怪段错误

c - printf 中的可变大小填充