I am trying to get the first value of a null initialed array of string.I have tried every method I can think of with no luck. I either get warning, errors, or a segmentation fault. Whats the correct way to print the null value and use it in the if statement?

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

int main(int argc, char** argv) 
{
    char *strings_line_tokens[503] = {0};
    strings_line_tokens[0] = malloc(strlen("cookies")+1);
    strcpy(strings_line_tokens[0], "cookies");
    printf("strings_line_tokens[]: %s\n",strings_line_tokens[0]);
    printf("-------------------\n");
    printf("strings_line_tokens[]: %c %d \n",(char)strings_line_tokens[1], (int)strings_line_tokens[1]);
    printf("aaaaaaaaaaaaaaaa\n");
    printf("strings_line_tokens[]: %c %d \n",strings_line_tokens[1], strings_line_tokens[1]);
    printf("bbbbbbbbbbbbbbbb\n");
    printf("strings_line_tokens[]: %c %d \n",(char)strings_line_tokens[1][0], (int)strings_line_tokens[1][0]);
    printf("ccccccccccccccccccc\n");
    printf("strings_line_tokens[]: %c %d \n",strings_line_tokens[1][0], strings_line_tokens[1][0]);
    printf("-------------------\n");
    if(strings_line_tokens[1] == 0)
    {
        printf("You have a NULL \n");
    }
    return 0;
}

Here are the current warning.

main.c:13: warning: cast from pointer to integer of different size
main.c:13: warning: cast from pointer to integer of different size
main.c:15: warning: format ‘%c’ expects type ‘int’, but argument 2 has type ‘char *’
main.c:15: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘char *’

Drop the second index. Because the value is NULL, which is the string terminator, basically you're asking to read the first character of a NULL string, which doesn't exist.

printf("strings_line_tokens[]: %c %d \n",(char)strings_line_tokens[1], (int)strings_line_tokens[1]);

As for detecting the NULL you can use 0 like you've done or you can make it easier to understand by using the null character(\0) or the NULL constant.

The warnings you're getting seem to be compiler setting specific. You should be able adjust the settings to remove them

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.