0

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);  
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • 1
    what exactly do you mean by *"return a pointer to char"*. your code really isn't returning anything. also, `a` needs to be `int` not `char` because `getchar()` returns an `int`. Also, [don't use gets](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used). It is dangerous and has been deprecated and even the documentation says don't use it. – MFisherKDX May 16 '19 at 18:49
  • Your `main()` has no return type. When a function doesn't take any parameters it's parameter list should be `void`: `int main(void)`. Also, the correct conversion specifier for pointer values for `*printf()` is `%p` not `%d`. – Swordfish May 16 '19 at 19:01
  • @MFisherKDX it was deprecated between 1999 and 2011, it is now removed – M.M May 16 '19 at 21:26

2 Answers2

2

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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • suggest: *just look for them from right after the last known occurrence.* *~>* "just look for them starting one to the right after the last known occurrence." – Swordfish May 16 '19 at 18:56
1

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278