Pelles C forum

C language => Beginner questions => Topic started by: bitcoin on March 20, 2022, 10:51:18 PM

Title: How to check all strings?
Post by: bitcoin on March 20, 2022, 10:51:18 PM
There is a task, you need to compare a string with an array of strings. I don't know if I'm doing the right thing. It works, but I would like it to be somehow more elegant .. I think this solution is redundant. Or is it ok?
Code: [Select]
char *data[] = { "data1", "data2", "data3", "data4", NULL };
char *p;
UINT i = 0;
do
{
p = data[i];
/* doing something with string */
i++;
} while (p!=NULL);
Title: Re: How to check all strings?
Post by: CLR on March 21, 2022, 01:34:03 AM
Hi bitcoin. I think it is OK.

I'd write

Code: [Select]
for (int i = 0; data[i] != NULL; i++){ /* do something with data[i] */}
Title: Re: How to check all strings?
Post by: 30f7r8d2 on March 21, 2022, 05:46:29 AM
Excuse me please but why there is NULL in *data[], isn't it an array of strings so there should be no need to NULL terminate it?

Code: [Select]
char *data[] = { "data1", "data2", "data3", "data4", NULL };
Title: Re: How to check all strings?
Post by: TimoVJL on March 21, 2022, 08:25:42 AM
This goes through strings.
Code: [Select]
#include <stdio.h>

char *data[] = { "data1", "data2", "data3", "data4", 0 };

int __cdecl main(void)
{
int i = 0;
while (data[i]) {
int j = 0;
while (data[i][j]) {
printf("%c ", data[i][j]);
j++;
}
printf("\n");
i++;
}
return 0;
}
Code: [Select]
d a t a 1
d a t a 2
d a t a 3
d a t a 4
Title: Re: How to check all strings?
Post by: bitcoin on March 21, 2022, 02:21:16 PM
TimoVJL , CLR
Thank you !

Excuse me please but why there is NULL in *data[], isn't it an array of strings so there should be no need to NULL terminate it?

Code: [Select]
char *data[] = { "data1", "data2", "data3", "data4", NULL };

Because how I can guess , where is the end of array?
There may be a different number of string. Do not manually enter the count.
Title: Re: How to check all strings?
Post by: AlexN on March 21, 2022, 04:09:16 PM
You can try this:
Code: [Select]
char *data[] = {"data1", "data2", "data3", "data4"};
count = sizeof(data)/sizeof(data[0]);
or make a macro:
Code: [Select]
#define COUNT(x) (sizeof(x)/sizeof(x[0]))

char *data[] = {"data1", "data2", "data3", "data4"};
count = COUNT(data);