0

In that link: Why can't we use double pointer to represent two dimensional arrays?

I saw that arrays are represented like this:

 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
| | | | | | | | | | | | | ..............| | | (10*6 elements of type int)
 - - - - - - - - - - - - - - - - - - - - - -
< first row >< second row> ...

Buy then I tried to do the next thing:

    char words[6][21];
    int i = 0;
    for (i = 0; i < 6; i++)
    {
        printf("Please enter word number %d: \n", i + 1);
        fgets(words[i], 21, stdin);
        words[i][strcspn(words[i], "\n")] = 0;
        putchar('\n');
    }
    printf("%d", (*(words + 0)));

As wrote in the link, if the input is:

123
654
555
444
888
666

Then the output should be '1'. But instead, the output is the memory adress. sombody can explain me the missundersood?

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
wv wv
  • 1

5 Answers5

2

The problem is that you wrote printf("%d", (*(words + 0)));

words+0 turn into words, so it's like `printf("%d", *words);

*words is like words[0] that is like &words[0][0] that is the address that printed.

you shoud change that to what that you want to print like:

printf("%c", **words)

to print the first char. remember that your array is char[][] so print this in "%c".

Roy Avidan
  • 769
  • 8
  • 25
1

Actually *words is the pointer to the first line of the two dimensional array words[][]. Since you just want an element, you need to type **(words + whatever)

PMonti
  • 456
  • 3
  • 9
1

You need to change :

printf("%d", (*(words + 0)));

to :

printf("%d", words[0][0]);

or :

printf("%d", **words);

or finally, to a more similar version to yours :

printf("%d", *(words[0] + 0));

Keep in mind that :

words[i][j]

is equivalent to :

*(words[i] + j)

as well as to :

*(*(words + i) + j)

Based on this, you can see that your statement :

printf("%d", (*(words + 0))); 

is the same as :

printf("%d", *words); 

or :

printf("%d", words[0]); 

which means that you print the address of the first array in words.


Also, you need to change the format specifier to %c, in order to specify that you print a char :

printf("%c", words[0][0]);
Marievi
  • 4,951
  • 1
  • 16
  • 33
1

if we consider words[6][21]

if you want to print 1

1.you should remember it is not integer it is char so you should %c instead of %d

  1. if you want to print words[0][0] equivalent word[i][j] is ((words+i)+j)

    so instead of writing (*(words + 0)) write ((words + 0))

ripazha
  • 11
  • 2
0

Your output format is incorrect.

printf("%d", (*(words + 0))); 

is equivalent to

printf("%d", *words);

which gives the address of the first array in the array-of-arrays.

Instead use printf("%d", words[0][0]); to print the first element.

Lundin
  • 195,001
  • 40
  • 254
  • 396