C语言不能用 == 比较字符串
两个代码,一样的功能,你喜欢第2个吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct String {
char* str;
int length;
} string;
string init(void) {
string s;
int len = 0;
s.str = malloc(len + 1);
s.str[0] = '\0';
s.length = len;
return s;
}
void add(string *s, char *elem) {
/*
int i = s->length;
do {
char* s.str = (char*)realloc(s.str, i*sizeof(i));
s.str[i] = *elem;
s.length = i;
i++;
} while(*elem != '\0')
*/
int length = strlen(s->str) + strlen(elem) + 1;
s->str = realloc(s->str, length);
strcat(s->str, elem);
}
int main(void) {
string a = init();
add(&a, "hello");
//if(a.str == "hello") // 这里为 false,不知道怎么了
if(!strcmp(a.str, "hello"))
printf("1");
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct String {char* str;
int length;} string;
string init(void) {
string s;
int len =0; s.str = malloc(len + 1);
s.str[0]= '\0'; s.length = len;
return s;
}
void add(string *s, char *elem)
{
/*
int i = s->length;
do {
char* s.str = (char*)realloc(s.str, i*sizeof(i));
s.str[i] = *elem;
s.length = i;
i++;
} while(*elem != '\0')
*/int length = strlen(s->str) + strlen(elem) + 1;
s->str = realloc(s->str, length);strcat(s->str, elem);}
int main(void) {
string a = init();add(&a, "hello");
//if(a.str == "hello") // 这里为 false,不知道怎么了
if(!strcmp(a.str, "hello"))
printf("1");
return 0;}
|