我使用C。我的两个字符串,与等于==运算符相比,并不匹配,即使std输出看起来是相同的。
假设其中一个数组作为整数数组启动,我通过向每个整数添加一个'0‘并将其加载到另一个char *数组将其转换为字符。
因此,现在这两个数组都是字符数组,具有相同的std输出,但我的"if“选择结构无法匹配它们。我使用char * name来引用每个数组。
如果有必要的话,我可以把整个代码都贴出来。下面是一个具有比较的循环:
i=0;
pipx = (char*)malloc(sizeof(char));
sec = (char*)malloc(sizeof(char));
//for (b = 0; b < lengthx; b++){
//reallocate a second array
pipx = (char*)realloc(sec, ((i+1)*sizeof(char)) );
sec = pipx;
//add bitstr[b] to second array
sec[i] = (char)bitstr[b] + '0';
i++;
for (m = 0; m < k; m++){
printf("codex[m].bitx:%s", codex[m].bitx);
printf("sec:%s|\n", sec);
printf("seclen: %i", (int)strlen(sec));
printf("codex[m].bitxlen: %i\n", (int)strlen(codex[m].bitx));
if ((char*)sec == (char*)codex[m].bitx){
printf("This should output: %s", sec);
printf("Here ---------------------- Here");
//allocate the second array to zero
i=0;
sec = (char*)malloc(0);
}
}
}发布于 2012-09-26 01:47:49
为了比较字符串,需要使用strcmp而不是==
==验证它们指向相同的地址,而strcmp将比较这两个字符*,如果每个字符匹配,则返回true,直到到达\0
发布于 2012-09-26 01:48:56
这是因为您在比较两个变量是否指向相同的内存地址,而不是两个内存地址上的信息是否相同。总是使用strcmp
发布于 2012-09-26 01:49:06
您正在比较文字指针值,而不是那些指针指向的字符串。
正如其他人所说,查找strcmp()和朋友。
https://stackoverflow.com/questions/12593453
复制相似问题