您的位置:首页 > 编程语言 > C语言/C++

字符串比较 c语言

2015-07-11 22:59 465 查看
[code]/*
    1. str1 和str2是两个数组,分配3个字符空间,并把"abc"的内容复制到数组中去,
    这是两个初始地址不同的数组,所以str1和str2的值是不同的
    2. str3和str4是两个指针,不需要为它们分配内存来存储字符的内容,
    只需要将它们指向"abc"中的内存中的地址就可以了,
    由于"abc"是常量字符串,在内存中是一个拷贝,
    所以str3和str4的值是相同的. 
*/
#include<stdio.h>

int main(void){
    char str1[] = "abc";
    char str2[] = "abc";

    char *str3 = "abc";
    char *str4 = "abc"; 

    if(str1 == str2){
        printf("\n str1 and str2 are same \n");
    }else{
        printf("\n str1 and str2 are not same \n");
    }

    if(str3 == str4){
        printf("\n str3 and str4 are same \n");
    }else{
        printf("\n str3 and str4 are not same \n");
    }
    return 0;
}


输出结果是:

[code]str1 and str2 are not same

str3 and str4 are same


原因:

1.str1 和str2是两个数组,分配3个字符空间,并把”abc”的内容复制到数组中去,

这是两个初始地址不同的数组,所以str1和str2的值是不同的



str3和str4是两个指针,不需要为它们分配内存来存储字符的内容,

只需要将它们指向”abc”中的内存中的地址就可以了,

由于”abc”是常量字符串,在内存中是一个拷贝,

所以str3和str4的值是相同的.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: