That code doesn't do what you expect at all. And WTH is char char *? This function's prototype should be:
Code:
int find_chr_index(const char *aeg, const int c)
There's no need to pass an int pointer to this function, and neither argument is to be modified within, so therefore you would qualify each as const.
Perhaps running this code and observing the output might help:
Code:
#include <stdio.h>
// Find the needle in the haystack.
int find_chr_index(const char *haystack, const int needle)
{
if (NULL == haystack)
{
printf("Invalid argument\n");
return -1;
}
printf("Memory address of variable 'haystack': 0x%x\n", &haystack);
printf("Memory address SAVED in variable 'haystack': 0x%x\n", haystack);
printf("Value of *haystack (contents of memory address saved in variable 'haystack': %c\n", *haystack);
// A convenience pointer, pointing to the start
// of the string we wish to search.
const char *p = haystack;
printf("Memory address of variable 'p': 0x%x\n", &p);
printf("Memory address SAVED in variable 'p': 0x%x\n", p);
printf("Value of *p (contents of memory address saved in variable 'p'): %c\n\n", *p);
// Our index counter.
int i = 0;
printf("Entering loop...\n");
// We will stop when we reach the character desired,
// or when we reach the NULL character that terminates
// this string.
while (NULL != p && '\0' != *p)
{
printf("\tMemory address of variable 'p': 0x%x\n", &p);
printf("\tMemory address SAVED in variable 'p': 0x%x\n", p);
printf("\tValue of *p (contents of memory address saved in variable p): %c\n\n", *p);
// If the character pointed to by p is equivalent
// to the character provided, we will return the value of our counter.
if (*p == needle)
return i;
// Increment the address saved in variable 'p' by the size
// of a character.
++p;
// Increment our counter.
++i;
}
return -1;
}
int main(void)
{
const char *testString = "This is a string with a q in it";
const char testChars[] = { 'q', 'g', 'z' };
int result = -1;
int i = 0;
for (; i < (sizeof(testChars) / sizeof(testChars[0])); ++i)
{
char testChar = testChars[i];
if (-1 == (result = find_chr_index(testString, testChar)))
printf("Did not find character %c\n\n", testChar);
else
printf("Found character %c at position %d\n\n", testChar, result);
}
return 0;
}