Reputation: 10466
Please have a look at the following code and tell me where does ***ptr
locates ?
i.e. i have a feelings that ***ptr
actually locates at ptr[0][0][0]
Am I wrong ? The following is a 3d representation of pointer. where I am trying to assign some characters and later i wanted to test what is the index of ***ptr
? will be waiting
#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();
}
Upvotes: 0
Views: 157
Reputation: 98358
First of all, I find your coding style extremely hard to read.
Answering your question, yes, ptr[0][0][0]
is a synonym of ***ptr
. Thats because a[b]
is by definition equal to *(a+b)
, so ptr[0]
is equal to *ptr
, etc.
Said that, here is my version of your code:
#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;
}
Note the following changes:
void main
in C or C++. And throw away any book that prints it.malloc
is usually the number of elements times the size of the element. Place special attention to the real type that you intend to use.malloc
is usually cast to the type pointer-to-the-type-of-the-element.i
and j
, not row
and rw
.*(ptr + x)
stuff? That's why we have the ptr[x]
syntax.strcpy
to fill your strings, but difficult to say without explaining the problem.printf
a pointer, use %p
.malloc
, include <stdlib.h>
.i
, j
) to global ones, particularly for loops.PS. <conio.h>
? Really? Are you still using Turbo-C or what?
Upvotes: 2