-
pointer problem
Hi all,
I have a problem with this code. Can somebody explain to me what this line does p = (char (*)[SZ])in;
I know that "in" is beeing casted but its strange when i see it with pointers. What is exactly happening in memory, what is p pointing at?
And also what is the difference between
char (*p)[SZ]; and char *p[SZ];
thx.
Code:
#include <stdio.h>
#define SZ 3
char print(char c) {
return c >= ' ' && c <= '~' ? c : '#';
}
void fooey(char *in, char *out, int size) {
char (*p)[SZ]; /*p points to array[s] of SZ chars each */
int r, c, i;
p = (char (*)[SZ])in;
for(c = i = 0; c < SZ; c++)
for(r = 0; r < size/SZ; r++, i++) {
out[i] = p[r][c] && p[r][c] != ' ' ? (p[r][c] | ' ') + 1 : p[r][c];
printf("%d=%c,(%d,%d)=%c\n", i, print(out[i]), r, c, print(p[r][c]));
}
}
int main( ) {
char test[9] = "NFCGNX N",
test2[sizeof test];
fooey(test, test2, sizeof test);
printf("%s\n", test2);
return 0;
}
-
The cast is used because 'in' is a pointer to char. It may be indexed like an array, but only in one dimension. The cast allows 'p' to be indexed as a two-dimensional array. For example, you can't do the following.
Code:
void fooey(char *in, char *out, int size) {
int r, c, i;
for(c = i = 0; c < SZ; c++)
for(r = 0; r < size/SZ; r++, i++) {
out[i] = in[r][c] && in[r][c] != ' ' ? (in[r][c] | ' ') + 1 : in[r][c];
printf("%d=%c,(%d,%d)=%c\n", i, print(out[i]), r, c, print(in[r][c]));
}
}
Using 'p' allows the two-dimensional indexing. But I don't believe this is in strict conformance with the standard (reference).
>And also what is the difference between
>char (*p)[SZ]; and char *p[SZ];
Code:
char (*p)[SZ]; /* p is a pointer to an array of SZ chars */
char *q [SZ]; /* q is an array of SZ pointers to char */
More info can be found here (near the bottom). It is a chapter from A TUTORIAL ON POINTERS AND ARRAYS IN C, which contains lots of good information. And even more information can be found here.