Excluded_Middle wrote:
> void main()
> {
> int i;
> int *x, *y;
> x = (int *) calloc(10, sizeof(int));
> for(i=0;i<10;i++)
> x[i] = i;
> }
>
This program is badly broken. See below.
> in the above program I want to to access x by pointer notation instead
> of array notation i.e. instead of using
>
> x[i] = i;
>
> I use
>
> *(x + i) = i;
> it doesn't work. secondly I use
What in the world do you mean by doesn't work? Of course it works:
#include <stdlib.h> /* mha: added; needed for OP's code */
#include <stdio.h> /* mha: not needed for the OP's code,
used to display the results of the
two approaches */
int /* mha: was the Schildty 'void' */ main()
{
int i;
int *x, *y;
/* mha: replaced wasteful calloc call, which also sillily cast the
return value from calloc */
if (!(x = malloc(10 * sizeof *x))) {
fprintf(stderr, " x allocation failed.\nQuiting");
exit(EXIT_FAILURE);
}
for (i = 0; i < 10; i++)
x[i] = i;
/* mha: the following is added to show the results of the assignments
both from the OP's code and from pointer-based assignments */
for (i = 0; i < 10; i++)
printf("x[%d] = %d\n", i, x[i]);
printf("\n");
/* mha: parallel to the above, but in using y, and running through
the arrays backward */
if (!(y = malloc(10 * sizeof *y))) {
fprintf(stderr, "allocation failed.\nQuiting");
free(x);
exit(EXIT_FAILURE);
}
for (i = 9; i >= 0; i--)
*(y + i) = i;
for (i = 9; i >= 0; i--)
printf("*(y+%d) = %d\n", i, y[i]);
printf("\n");
free(y);
free(x); /* mha: added, needed in OP's code */
return 0; /* mha: added, needed in OP's code
unless he has a C99 compiler */
}
[output]
x[0] = 0
x[1] = 1
x[2] = 2
x[3] = 3
x[4] = 4
x[5] = 5
x[6] = 6
x[7] = 7
x[8] = 8
x[9] = 9
*(y+9) = 9
*(y+

= 8
*(y+7) = 7
*(y+6) = 6
*(y+5) = 5
*(y+4) = 4
*(y+3) = 3
*(y+2) = 2
*(y+1) = 1
*(y+0) = 0