C比较指针(带字符) [英] C comparing pointers (with chars)
问题描述
晚上好,我有 2 个函数,每个函数都接受一个指向 char 的指针作为参数:
Good evening, I have 2 functions and each of them accepts as argument a pointer to char:
char pointer[255];
func1(char* pointer)
{
...
memcpy(pointer,some_char,strlen(something));
return;
}
func2(char* pointer)
{
...
if (pointer==someother_char) exit(0); //FAILs
//also I have
if(pointer==someother_pointer2char); // FAILs
}
现在我尝试了 strstr,strcmp 等...不起作用.想尝试 memcmp 但我没有静态 len.因为我必须将 char* 与 char 和 char* 与 char* 进行比较,所以我需要两种解决方案,对吗?
Now I've tried strstr,strcmp etc... doesn't work. Wanted to try memcmp but I don't have static len. As I have to compare char* to char and char* to char* I would be needing two solutions right?
那么,如何以最短的方式比较这些指针(实际上是指针)?
谢谢.
编辑
感谢 wallacer 和 Code Monkey 现在进行 char* 到 char 的比较,我使用以下方法:
func1(char* ptr){
char someother_char[255];
char *ptr_char = NULL; //I have to strcmp a few values so this is why I initialize it first
...
ptr_char = someother_char;
if (strcmp(ptr,ptr_char) == 0) //gtfo and it does...
...
ptr_char = some2nd;
if(strcmp...
可能有任何建议...(用于比较的外部函数?)
Any suggestions maybe... (hmm external function for comparing?)
建议 1(来自 Code Monkey)
#include <stdio.h>
int main(void) {
char tempchar[255];
tempchar[0] = 'a';
tempchar[1] = 'b';
tempchar[2] = ' ';
char *ptr_char;
ptr_char = &tempchar[0];
printf("%s", ptr_char);
return 0;
}
推荐答案
你需要使用strcmp
.没有看到您尝试使用它的方式,这就是您应该使用它的方式:
You need to use strcmp
. Not seeing how you tried to use it, this is how you should use it:
char *someother_char = "a";
char *pointer = "a";
if (strcmp(pointer, someother_char) == 0) { // match!
}
else { // not matched
}
要与 char
进行比较,您必须提升为 char*
:
to then do the comparison with a char
, you have to promote to a char*
:
char *someother_char1;
char test = 'a';
char *pointer = "a";
strncpy((char*)test,someother_char1,sizeof(test));
if (strcmp(pointer, someother_char1) == 0) { // match!
}
else { // not matched
}
如果你想使用 char
array 那么你必须取消引用:
if you want to use the char
array then you have to de-reference:
char char_array[255];
// don't forget to fill your array
// and add a null-terminating char somewhere, such as char_array[255] = ' ';
char *ptr_somechar = &char_array[0];
char *pointer = "a";
if (strcmp(pointer, ptr_somechar) == 0) { // match!
} else { // not matched
}
这篇关于C比较指针(带字符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!