c語言之創建字符串的兩種方式


在c語言中,一般有兩種方式來創建字符串

//第一種,利用字符指針
char* p = "hello";
//第二種:利用字符數組
char str[] = "hello";

那么,它們之間有什么區別呢?以例子說明:

#include<stdio.h>
#include<iostream>
char* returnStr()
{
    char* p = "hello world!";
    return p;
}
int main()
{
    char* str = NULL;
    str = returnStr();
    printf("%s\n", str);
    system("pause");
    return 0;
}

輸出:

 

以上代碼是沒有問題的,"hello world"是一個字符串常量,存儲在常量區,p指針指向該常量的首字符的地址,當returnStr函數退出時,常量區中仍然存在該常量,因此仍然可以用指針訪問到。

#include<stdio.h>
#include<iostream>
char* returnStr()
{
    char p[] = "hello world!";
    return p;
}
int main()
{
    char* str = NULL;
    str = returnStr();
    printf("%s\n", str);
    system("pause");
    return 0;
}

輸出:

 

以上代碼有問題,輸出為亂碼。這一段代碼和之前的最主要的區別就是returnStr中字符串的定義不同。這里使用字符數組定義字符串。因此這里的字符串並不是一個字符串常量,該字符串為局部變量,存查在棧中,當returnStr函數退出時,該字符串就被釋放了,因此再利用指針進行訪問時就會訪問不到,輸出一堆亂碼。

當然 ,如果將char p[] = "hello world!";聲明為全局變量,即:

#include<stdio.h>
#include<iostream>
char p[] = "hello world!";
char* returnStr()
{
    return p;
}
int main()
{
    char* str = NULL;
    str = returnStr();
    printf("%s\n", str);
    system("pause");
    return 0;
}

那么,該字符串就會存儲在全局變量區,一般將全局變量區和靜態資源區和常量區視為一個內存空間。因此,同樣可以使用指針訪問到。

輸出:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM