簡體   English   中英

將目標字符串作為 strcpy 中的指針傳遞

[英]Passing destination string as a pointer in strcpy

最近知道了一個叫做strcpy的函數, strcpy的語法是char*strcpy(char * destination,const char * source) ,所以目標字符串可以是指向 char 的指針,但是我的代碼的輸出是 null ,為什么?

#include <stdio.h>
#include <string.h>

//Compiler version gcc  6.3.0

int main()
{
  char *text1;
  char text2[]="ahhabsha";
  strcpy(text1,text2);
  printf("%s",text1);
  return 0;
}

所以目標字符串可以是指向 char 的指針

不,目標字符串不能是指針。

目標必須是字符類型的連續內存區域。 第一個函數參數是指向該區域的指針。

您的代碼正確傳遞了一個字符指針,但問題是該指針指向任何內存。

通常有兩種方法可以做到這一點。

  1. 分配動態內存,如:

     char text2[]="ahhabsha"; char* text1 = malloc(sizeof text2); // or malloc(1 + strlen(text2)); ... ... free(text1);
  2. text1更改為字符數組而不是字符指針

    char text2[]="ahhabsha"; char text1[sizeof text2];

在第二種情況下,當您調用strcpy時, text1會自動從“字符數組”轉換為“字符指針”

順便提一句:

在許多系統上還有非標准的strdup函數。 它執行內存分配和字符串復制,因此您無需調用strcpy 喜歡:

    char text2[]="ahhabsha";
    char* text1 = strdup(text2);
    printf("%s\n", text1);
    free(text1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM