how can i add '\0' at the end of a string which is referred to using a pointer?

StackOverflow https://stackoverflow.com/questions/21638326

  •  08-10-2022
  •  | 
  •  

سؤال

I want to check if string b is suffix of string a. I have tried this so far:

    char a[20], b[20];
    char *p;
    gets(a);
    gets(b);

    p = strstr(a,b);
    while(p != NULL)
    {
        if(p + strlen(b) == '\0')
            break;
        p = strstr(p+1, b);
    }

I have opened the debugger and have seen that when the program reaches this line:

if(p + strlen(b) == '\0')

It never validates to true because p + strlen(b) isn't \0 but just \.

How can I add \0 at the end of what p is pointing to?

هل كانت مفيدة؟

المحلول

You need to derfernce the pointer that you are computing:

Either

if(*(p + strlen(b)) == '\0')

or

if(p[strlen(b)] == '\0')

should do it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top