I am writing code that searches a string for a specified character and returns its position in the array. Here's my code so far:
Code:
#include <stdio.h>
#include <string.h>
int check_for_label (char str[])
{
char * pch;
int i;
for (pch = strchr (str, ':'); pch != NULL; pch = strchr (pch + 1,':'))
{
i = pch - str + 1;
}
return i;
}
int main ()
{
int h;
char label[5];
char str[] = "for :add $2, $3, $4";
h = check_for_label (str);
printf ("%d\n", h);
return 0;
}
When I run it with the colon in the array, h = 5, and when there's is no colon, h = 0. But when I try to integrate the function into another program, instead of returning h = 0, it returns some random numbers, like 11824 etc instead of 0, but still returns correct h value if there's a colon. I understand that function strchr returns NULL if no matching character is found, so could this be the problem?