c指针理解问题

标签 c pointers

请看下面的代码,告诉我***ptr 在哪里? 也就是说,我觉得 ***ptr 实际上位于 ptr[0][0][0] 我错了吗 ?以下是指针的 3d 表示。我试图在其中分配一些字符,后来我想测试什么是 ***ptr 的索引?将等待

#include<stdio.h>
#include<conio.h>
#define row 5
#define rw 3
#define col 10


char ***ptr;
int i,j,k;


void main()
{

clrscr();

ptr=(char *)malloc(row*sizeof(char *));

for(i=0;i<row;i++)
    {
        *(ptr+row)=(char *)malloc(rw*sizeof(char *));
        printf("\t:\n");

           for(j=0;j<rw;j++)
           {
           *(*(ptr+row)+rw)=(char *)malloc(col*sizeof(char *));
           if(i==0 && j==0)
               {       //   *(*(ptr+row)+rw)="kabul";
            **ptr="zzz";

               }
           else
            *(*(ptr+row)+rw)="abul";
           printf("\taddress=%d %d%d = %s\n",((ptr+row)+rw),i,j,*(*(ptr+row)+rw));

           }

         printf("\n");
    }


printf("%c %d",***ptr,ptr);
getch();
}

最佳答案

首先,我发现您的编码风格非常难以阅读。

回答你的问题,是的,ptr[0][0][0]***ptr 的同义词.那是因为a[b]根据定义等于 *(a+b) , 所以 ptr[0]等于*ptr

也就是说,这是我的代码版本:

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#define row 5
#define rw 3
#define col 10


char ***ptr;

int main()
{
    int i, j;

    ptr = (char***)malloc(row * sizeof(char **));

    for(i = 0; i < row; i++)
    {
        ptr[i]= (char**)malloc(rw * sizeof(char *));
        printf("\t:\n");

        for(j = 0; j < rw; j++)
        {
            ptr[i][j] = (char*)malloc(col * sizeof(char));
            if (i == 0 && j == 0)
            {
                strcpy(ptr[i][j], "zzz");
            }
            else
            {
                strcpy(ptr[i][j], "abul");
            }
            printf("\taddress=%p %d,%d = %s\n", ptr[i][j], i, j, ptr[i][j]);

        }
        printf("\n");
    }
    return;
}

注意以下变化:

  • 永远不要写void main在 C 或 C++ 中。扔掉任何打印它的书。
  • malloc 的参数通常是元素的数量乘以元素的大小。请特别注意您打算使用的真实类型。
  • 返回malloc通常被转换为类型指向元素类型的指针
  • 数组中的索引应该是ij , 不是 rowrw .
  • 为什么所有*(ptr + x)东西?这就是为什么我们有 ptr[x]语法。
  • 你可能想使用 strcpy填补你的字符串,但如果不解释问题就很难说。
  • 当你想printf指针,使用 %p .
  • 如果您使用 malloc , 包括 <stdlib.h> .
  • 优先使用局部变量( ij )而不是全局变量,尤其是循环。
  • 还有一些其他的小改动...

附言。 <conio.h> ?真的吗?您还在使用 Turbo-C 还是什么?

关于c指针理解问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7855161/

相关文章:

c - Linux内核中ALIGN()和round_up()宏的区别

c - 通过引用传递 C 指针?

c - 为什么我必须返回指针?

C取消引用指针警告,甚至认为它们都是字符

c - C 中的 Strcmp 不工作

c - 如何将内存数据从指针复制到数组 ASSEMBLY 8086

c - 为什么 typedef'ing 会导致具有引用自身字段的结构出错?

c - 2 个可执行文件的 Makefile 错误 : multiple definitions of 'main'

c++ - 如何使用数组将多个字符串文字传递给函数(无 vector )

c++ - 为什么这个结构没有在函数中设置