C比较指针(带字符)

标签 c string pointers compare

晚上好,我有 2 个函数,每个函数都接受一个指向 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* 与 charchar* 与 char* 进行比较,所以我需要两种解决方案,对吗?

那么,如何以尽可能短的方式比较这些指针(实际上是指针)?

谢谢。

编辑

现在感谢 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...

可能有什么建议......(嗯,用于比较的外部函数?)

建议 1(来自 Code Monkey)

#include <stdio.h>

int main(void) {
    char tempchar[255];
    tempchar[0] = 'a';
    tempchar[1] = 'b';
    tempchar[2] = '\0';
    char *ptr_char;
    ptr_char = &tempchar[0];
    printf("%s", ptr_char);
    return 0;
}

最佳答案

您需要使用strcmp。没有看到您尝试使用它的方式,这就是您应该如何使用它:

char *someother_char = "a";
char *pointer = "a";

if (strcmp(pointer, someother_char) == 0) { // match!
}
else { // not matched 
}

然后要与 char 进行比较,您必须提升为 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 那么你必须取消引用:

char char_array[255];
// don't forget to fill your array
// and add a null-terminating char somewhere, such as char_array[255] = '\0';
char *ptr_somechar = &char_array[0];
char *pointer = "a";

if (strcmp(pointer, ptr_somechar) == 0) { // match!
} else { // not matched
}

关于C比较指针(带字符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7125697/

相关文章:

c# - 有没有适用于触摸屏手机的代码编辑器?

java - 替换由开始和结束索引点定义的子字符串?

java删除空格也会删除空格后的所有内容

c++ - 从方法返回指针

c - C中带指针的for循环

c - 是否有 libc 函数(或等效函数)可以知道堆的当前大小?

c - 将文件中的字符串读取到数组中

java - 如何解析字符串以分隔整数? java

c - JNI 将 Char* 二维数组传递给 JAVA 代码

c++ - WIN32 API 项目中的 ReadDirectoryChangesW 错误?