0

Say if I have : unsigned char* str = "k0kg"

And 0 is the null element. When I loop through it using a for loop, how do I check if the array has a null?

I tried: if (str[1]==0): I also tried: if (str[1]=="0"):

And they didn't work. :(

The loop:

for (i=0;i<num_bytes;i++){
    if (str[i]!=0){
        printf("null spotted\n");
}
3
  • "0" is character zero, aka ascii char 48 (0x30 hex). 0 is value zero, aka null/false Commented Feb 7, 2014 at 0:29
  • @MarcB to be 100% correct, you should use single quotes, not double. Commented Feb 7, 2014 at 0:39
  • @MarcB: To be correct at all, you should use single quotes. Commented Feb 7, 2014 at 0:57

4 Answers 4

3

In C, strings, by definition, are terminated by '\0', the NUL character. So all (valid) strings have a '\0' in them, at the end.

To find the position of the '\0', simply use strlen():

const char * const end = str + strlen(str);

It's odd that you are using "unsigned char" if you are dealing with normal, printable strings. If you mean that you have a memory block with bytes it in and you want to find the first 0x00 byte, then you'll need a pointer to the start of the memory and the size of the memory area, in bytes. Then, you'd use memchr():

// Where strSize is the number of bytes that str points to.
const unsigned char * const end = memchr(str, 0, strSize);
Sign up to request clarification or add additional context in comments.

Comments

2

If you are actually looking for the null element then you should do the following condition :

if(str[i]=='\0')

Comments

1

Say if I have : unsigned char* str = "k0kg"

And 0 is the null element. When I loop through it using a for loop, how do I check if the array has a null?

You're terminology is going to confuse any C programmer. You're confusing character representations with values. You're not looking for a null character ("null element", which would be '\0'), you're looking for the character '0'. So...

int len = strlen(str);
for(int i = 0; i < len; ++i) {
    if(str[i] == '0')
        printf("found it");
}

Comments

0

use strchr

#include <stdio.h>
#include <string.h>

int main(){
    char *str = "k0kg";
    char *p = strchr(str, '0');
    if(p){
        printf("find at %d\n", (int)(p - str));//find at 1
    }
    if(p=strchr(str, 0)){
        printf("find at %d\n", (int)(p - str));//find at 4
    }
    str = "k\0kg";
    if(p=strchr(str, 0)){
        printf("find at %d\n", (int)(p - str));//find at 1
    }

    return 0;
}

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.