简体   繁体   中英

Char array pointer in C

I want to run this code but i can not. i have yet started to learn pointer in C. I am trying to get the addresses of letters. Problem is printf("in adress: %p\\n",p[i]) ;` Thanks

#include <stdio.h>

int main(void){
    char letter;
    int c=0;
    int i;
    char pattern[7];
    char *p;
    printf("Enter a letter: ");
    scanf("%c",&letter);
    printf("Enter a pattern: ");
    scanf("%s",pattern);
    p=pattern;
    for(i=0;i<7;i++)
    {
        if(letter==pattern[i])
        {
            c++;
            printf("Letter < %c > is found in pattern %s\n",letter,pattern);
            printf("in adress: %p\n",p[i]);
            printf("index:%d\n",i);
        }

    }
    if(c==0)
        printf("The pattern does not include any letter");

  return 0;
}

This line of code has some potential problem that can easily happen

scanf("%s",&pattern);

you can make it a little bit safer like this

scanf("%6s",&pattern);

it's a 6 because you need one extra byte '\\0' at the end of the string, which takes us to the next problem

for(i=0;i<7;i++)

here you are assuming that all bytes are non- nul which would be ok except that you are reading a string with scanf() and unless you create the array one byte bigger than the number of characters you want to store in it, scanf() will overflow the array ie write a byte beyond it's bounds.

Adding the "%6s" length specifier to the format string solves this, but you can only store 6 non- nul bytes in the array, and for the other problem

for (i = 0 ; pattern[i] != '\0' ; i++)

would be better, because you don't need to know the length of the string in advance and you don't risk reading past the end of the array.

Try this:

#include <stdio.h>

int main(void)
{
    char  letter;
    char  c;
    int   i; 
    char  pattern[7];
    printf("Enter a letter: ");
    if (scanf(" %c",&letter) != 1)
     {
        printf("error: invalid input.\n");
        return -1;
     }
    printf("Enter a pattern: ");
    if (fgets(pattern, sizeof(pattern), stdin) == NULL)
     {
        printf("error: end of file.\n");
        return -1;
     }
    for (i = 0 ; pattern[i] != 0 ; ++i)
    {
        if (letter == pattern[i])
        {
            c++;
            printf("Letter < %c > is found in pattern %s\n", letter, pattern);
            printf("in adress: %p\n", pattern + i);
            printf("index    :%d\n", i);
        }

    }
    if (c == 0)
        printf("The pattern does not include any letter");
    return 0;
}

You also was printg the address wrong, because in pointer[i] the subscript operator dereferences the pointer, it's equivalent to *(poitner + i) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM