简体   繁体   中英

How to find base address of same char in string array using pointers in C language?

I input a string and then try to find an address of a char within the string but the problem is that I am unable to find the address of the same char in the string using pointers.

For example when input is "ALLEN" I need the addresses of both 'L' s but my program only prints the address of the first 'L' .

I tried if ... else and a for -loop but I can't solve the problem.

#include <stdio.h> 
#include <string.h> 


main() 
{ 
    char a, str[81], *ptr;

    printf("\nEnter a sentence:");
    gets(str); 

    printf("\nEnter character to search for:");
    a = getchar(); 
    ptr = strchr(str,a);

     /* return pointer to char*/ 

    printf( "\nString starts at address: %d",str);
    printf("\nFirst occurrence of the character (%c) is at address: %d ", a,ptr);  
}

If I understood you correctly:

To find additional occurrences of the same character, just look for them after the last known occurrence. So, you would write something like this:

{
    const char* next_occurrence = strchr(str, a);
    while (next_occurrence != NULL) {
        printf(
            "Character %c occurs in string \"%s\" at position %p\n",
            a, str, next_occurrence - str);
        next_occurrence = strchr(next_occurrence + 1, a);
    }
}

You'll note that next_occurrence + 1 is the address of the first character after the occurrence we've just found.

Just call strchr again:

ptr = strchr(str,a);
if (ptr != NULL)
    ptr2 = strchr (ptr + 1, a);

Notice the first parameter to strchr is ptr + 1 , so we start searching with the character after the one we already found.

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