1

Hey I am trying to understand pointers and I create a program in which I give words from keywords and I store them in an array and after that I want to print the first character of the first word (I expected) but it prints the first character of the second word

What is going wrong?

#include<stdio.h>
#include<stdlib.h>

int main ()
{
    
    int i=0;
    char array[5][10];
    
    for(i = 0 ; i < 5 ; i++)
    {
        gets(array[i]);
    }
    printf("\n");
    char *p;
    p=&array[0][10];
    printf("%c",*p);
    
    
    return 0;
}
vgag1997
  • 31
  • 1
  • 2
    The first character of the first string is `array[0][0]` – Retired Ninja May 31 '21 at 22:00
  • And fyi, `p=&array[0][10];` arrays of size `N` are are indexible 0..(N-1) . This indexing within the first array in your array of arrays breaches. Unrelated, stop using `gets`. It is so evil it isn't even part of the standard library anymore. Use `fgets` instead. – WhozCraig May 31 '21 at 22:00
  • Why do you think `array[0][10]` refers to the first character of the first word? Did you mean `array[0][0]` instead? Also, read this: [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036/10871073) – Adrian Mole May 31 '21 at 22:01
  • Are this kind of questions allowed? – Miguel Sandoval May 31 '21 at 22:01
  • @DavidSais A *well-asked* question about why a program doesn't work is allowed. However, when the problem can be resolved by correcting a simple 'typo', the question can be closed by 3 votes. – Adrian Mole May 31 '21 at 22:03
  • 1
    @DavidSais it has a complete program, which is more than can be said for a lot of questions – M.M May 31 '21 at 22:49
  • Ok, good to know – Miguel Sandoval Jun 01 '21 at 14:26

2 Answers2

2

The position in the array you are looking for doesn't exist, so the program is showing a random value.
The arrays go from 0 to (n-1), 'n' being 5 or 10 in your case. If you search a differente position in the range of the array you will find the correct answer.
Try changing this part of the code ('a' have to be a value from 0 to 4 and 'b' have to be a value from 0 to 9)

p=&array[a][b];
Rlyra
  • 86
  • 5
  • Not sure about 'random' value - IIRC, 2D arrays in C are *contiguous* blocks of data. That being said, attempting to access `array[0][10]` still smells like undefined behaviour. – Adrian Mole May 31 '21 at 22:54
  • Yes, 'random' is not the correct way to put it. The correct term is undefined behavior, you are right. – Rlyra May 31 '21 at 22:57
1

pointer are address in memory

1rst word adresses are from 0 to 9

2nd word from 10 to 19

p=&array[0][10]; points to the 10th elt so the first letter of the second word! and not for a random value as previous post suggests.

That said NEVER use gets

Why is the gets function so dangerous that it should not be used?

Dri372
  • 1,275
  • 3
  • 13