I'm trying to write a code in c that return 1 if there is "&" in the string and 0 otherwise. In addition, the char*
that I receive in the function I want to put it in an array of chars and NULL in the end. My code is like this:
char** isBackslash(char* s1, int *isFlag) {
int count = 0;
isFlag = 0;
char **s2[100];
char *word = strtok(s1, " ");
while (word != NULL) {
s2[count] = word;
if (!strcmp(s2[count], "&")) {
isFlag = 1;
}
count++;
word = strtok(NULL, " ");
}
s2[count] = NULL;
return s2;
}
For example, if the original string (s1) is "Hello I am John &".
So I want s2 to be like:
s2[0] = Hello
s2[1] = I
s2[2] = am
s2[3] = John
s2[4] = &
s2[5] = NULL
And the function will return '1'. What is wrong with my code? I debugged it and unfortunately, I don't find the problem.
You were shadowing your own parameter. See a working example below:
#include <stdio.h>
#include <string.h>
#define BUFF_SIZE 256
int isBackslash(char* s1, char s2[][BUFF_SIZE]) {
int isFlag = 0;
int i = 0;
int j = 0;
int n = 0;
while (s1[i] != '\0') {
isFlag |= !('&' ^ s1[i]); // will set the flag if '&' is met
if (s1[i] == ' ') {
while (s1[i] == ' ')
i++;
s2[n++][j] = '\0';
j = 0;
}
else
s2[n][j++] = s1[i++];
}
return isFlag;
}
int main(void) {
char s2[BUFF_SIZE/2+1][BUFF_SIZE];
memset(s2, 0, sizeof(s2));
char s1[BUFF_SIZE] = "Hello I am John &";
int c = isBackslash(s1, s2);
printf("%d\n", c);
int i = 0;
while (s2[i][0] != '\0')
printf("%s\n", s2[i++]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.