0

I'm having some problems with a simple function call I'm trying to write; basically, the function takes a string and a character argument and returns a pointer to the first instance of that character in the string. The call in this instance uses a for loop to use pointers to strings to print out 4 strings. I've tried fiddling around with a bunch of things but can't get the function and call to work. Any help would be greatly appreciated.

#include <stdio.h>
#define NUMBER 4

char * strsrch(char * string, char x);
int main(void)
{
    char * ptr[NUMBER];
    int x;
    char * word[NUMBER] = {"This is string 1", "Now string 2", "Proceeding through string 3", "And then, the last string"};
    for(x = 0; x < NUMBER; x++)
        puts(word[x]);
    for(x = 0; x < NUMBER; x++)
        puts(strsrch(word[x], 'i'));


    return 0;
}

char * strsrch(char * string, char x)
{
    while (*string && (*string != x))
        string++;

    if (*string = x)
        return string;
    else
        return NULL;

}
1
  • Would abort during the .exe. Fixed now though. Commented Aug 7, 2011 at 2:23

3 Answers 3

9

This if (*string = x) should be if (*string == x)

You assigned x to *string instead of comparing them .

Sign up to request clarification or add additional context in comments.

7 Comments

FUUUUUUUUUUU not again!! Thanks!
@Matt - the speed of answer indicates the number of time I did it :)
@Matt: You really should turn up the warning level on your compiler, since all modern compilers will warn about that exact problem if you enable it.
@Greg Hewgill: Is there a good read on enabling compiler warnings?
@Greg Hewgill: That's a good idea, will probably save me a lot of time, thanks!
|
3

It should be:

if (*string == x)

Comments

2

You have done if (*string = x) which will assign the character (value) of x into the location pointed by string , and if x is not 0 then this if will be always true. You wanted to compare the value of x and the first character of string which is done by if (*string == x) . This will compare the values.

To avoid such mistakes/typos, in such cases you can define the char * as constant to forbid accidental modification of the values which you do not want to be changed. For example in this case you can define your function like:

char * strsrch(const char * string, char x);

This will stop you from assigning the value of x into the string at the time of compilation.

Also you can use more warning level with your compiler. For example with gcc turning on -Wall will warn you about the assignment .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.