gpt4 book ai didi

C比较指针(带字符)

转载 作者:太空狗 更新时间:2023-10-29 16:40:27 25 4
gpt4 key购买 nike

晚上好,我有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com