vgag1997
vgag1997

Reputation: 31

Why my program prints the wrong character?

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;
}

Upvotes: 1

Views: 108

Answers (2)

Dri372
Dri372

Reputation: 1321

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?

Upvotes: 1

Rlyra
Rlyra

Reputation: 86

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];

Upvotes: 2

Related Questions