Euclid Ye
Euclid Ye

Reputation: 521

After malloc the string how to compare it with null

a short question here.

I do know that if I declare something like

char* a[1024];

Then I can compare a[i] with null;

if(a[i])

However, if I malloc every element in a, then I may not do it...

The only way I can find out to compare it with empty is the following:

if(strcmp(a[i],"")!=0)

But I feel it is stupid and there must be more elegant way to do the comparison...

Any suggestions?

Thanks!

PS: I need to do malloc because I would do strtok. And I want to strcat something to the result, so I cannot just use a[i] as a pointer to the the result, but need to copy the content.

Upvotes: 3

Views: 716

Answers (4)

Sai Seshu Chadaram
Sai Seshu Chadaram

Reputation: 1

Try this code..if(!a[i]) condition works when a[i] is NULL

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int i;
    char *a[10];
    for(i=0;i<10;i++)
        a[i]=(char *)malloc(10);
    a[0]=NULL;
    a[1]="some text";
    if(!a[0])
        printf("a[0] is null value\n");
    else
        printf("a[0] is not null value\n");
    if(!a[1])
        printf("a[1] is null value\n");
    else
        printf("a[1] is not null value\n");
    return 0;
}

Upvotes: 0

user3386109
user3386109

Reputation: 34839

The strcmp is fine, but you can also do

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

to see if a string is empty.

This assumes that you've put something in the string after calling malloc, e.g.

a[i] = malloc(...);
a[i][0] = '\0';

or

ptr = strtok(...);
a[i] = malloc(...);
strcpy( a[i], ptr );

Upvotes: 3

collapsar
collapsar

Reputation: 17258

Use calloc Instead of malloc. Thus your string chars are initialized to \000 and you can test for it with if (a[i][0]).

Upvotes: 1

Paul92
Paul92

Reputation: 9082

If you say you allocate every element of a with malloc, then you should have something like:

for (int i = 0; i < 1024; i++) {
    a[i] = malloc(size);

Given this, why don't you test for the value of a[i]:

    if (a[i])
        // error
}

Upvotes: 0

Related Questions