我知道为了比较C中的两个字符串,您需要使用该strcmp()
函数.但我试图将两个字符串与==
运算符进行比较,并且它有效.我不知道如何,因为它只是比较两个字符串的地址.如果字符串不同,它应该不起作用.但后来我打印了字符串的地址:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* str1 = "First";
char* str2 = "Second";
char* str3 = "First";
printf("%p %p %p", str1, str2, str3);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
00403024 0040302A 00403024
Process returned 0 (0x0) execution time : 0.109 s
Press any key to continue.
Run Code Online (Sandbox Code Playgroud)
怎么可能str1
和str3
具有相同的地址?它们可能包含相同的字符串,但它们不是同一个变量.
当我在我的Linux x86_64机器上编译并运行以下C程序时,由GCC编译:
#include <stdio.h>
int main(void)
{
char *p1 = "hello"; // Pointers to strings
char *p2 = "hello"; // Pointers to strings
if (p1 == p2) { // They are equal
printf("equal %p %p\n", p1, p2); // equal 0x40064c 0x40064c
// This is always the output on my machine
}
else {
printf("NotEqual %p %p\n", p1, p2);
}
}
Run Code Online (Sandbox Code Playgroud)
我总是得到输出:
等于0x40064c 0x40064c
我知道字符串存储在一个常量表中,但与动态分配的内存相比,地址太低了.
与以下程序比较:
#include <stdio.h>
int main(void)
{
char p1[] = "hello"; // char arrar
char p2[] = …
Run Code Online (Sandbox Code Playgroud) 为什么它可行?有两个不同的字符串,"testString"
但矢量大小正确分配.
#include <iostream>
#include <vector>
#include <iterator>
int main()
{
std::vector<char> str;
str.assign(std::begin("testString"), std::end("testString"));
copy(str.begin(), str.end(), std::ostream_iterator<char>(std::cout, " "));
std::cout<<str.size();
return 1;
}
Run Code Online (Sandbox Code Playgroud) #include <stdio.h>
int main(){
char a[] = "bar";
char b[] = "bar";
printf("%d\n", (a==b));
char* x = "bar";
char* y = "bar";
printf("%d\n", (x==y));
}
Run Code Online (Sandbox Code Playgroud)
输出:
0
1
Run Code Online (Sandbox Code Playgroud)
我知道我们无法使用==
运算符比较C char数组,因为它比较了内存位置,但为什么它在第二种情况下有效呢?
我有点困惑.我有以下功能:
int comp(char s1[], char s2[]) {
return s1 == s2;
}
Run Code Online (Sandbox Code Playgroud)
据我所知,这只比较了char数组s1
和char数组中第一个元素的地址s2
.
但奇怪的是,如果我比较(在Visual Studio中)两个相等的char数组
comp("test","test");
Run Code Online (Sandbox Code Playgroud)
我得到1(真)而不是0(假).但是地址不应该不同,因此结果应该始终为0吗?
代码是:
#include<stdio.h>
int main()
{
char *st1="hello";
char *st2="hello";
if(st1==st2)
printf("equal %u %u",st1,st2);
else
printf("unequal");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到输出"相等4206628 4206628".
当我明确说明字符串的值,然后将其与自身进行比较时,系统返回FALSE.这是否与系统添加的额外'\ 0'字符有关?我应该如何优化我的代码使其成为正确的?
char name[5] = "hello";
if(name == "hello")
{
...
}
Run Code Online (Sandbox Code Playgroud) c ×7
string ×5
arrays ×3
c++ ×2
gcc ×2
pointers ×2
char ×1
character ×1
comparison ×1
compilation ×1
linux ×1
memory ×1
performance ×1
vector ×1