簡體   English   中英

如何將值分配給const char *數組並打印到屏幕

[英]How to assign values to const char* array and print to screen

盡管我使用的是C ++,但作為要求,我需要使用const char *數組而不是字符串或char數組。 由於我是新手,因此我需要學習如何使用const char *。 我已經將我的const char *數組聲明為const char* str[5] 在程序的后面,我需要用值填充5個元素中的每個元素。

但是,如果我嘗試分配這樣的值:

const char* str[5];
char value[5];
value[0] = "hello";
str[0] = value[0];

它不會編譯。 將char數組中的char數組添加到const char *數組然后打印該數組的正確方法是什么? 任何幫助,將不勝感激。 謝謝。

  1. 字符串"hello"由6個字符組成,而不是5個字符。

     {'h', 'e', 'l', 'l', 'o', '\\0'} 
  2. 如果在聲明value時分配字符串,則代碼看起來類似於當前的代碼:

     char value[6] = "hello"; 
  3. 如果要在單獨的兩行中執行此操作,則應使用strncpy()

     char value[6]; strncpy(value, "hello", sizeof(value)); 
  4. 將指向value的指針放置在名為str的字符串列表中:

     const char * str[5]; char value[6] = "hello"; str[0] = value; 

    注意,這會給str[1]str[4]留下未指定的值。

稍后會在程序中指出各種填充const char* str[5]的方法。

int main(void) {
  const char* str[5];

  str[0] = "He" "llo";  // He llo are string literals that concat into 1

  char Planet[] = "Earth";  
  str[1] = Planet;  // OK to assign a char * to const char *, but not visa-versa

  const char Greet[] = "How";
  str[2] = Greet;

  char buf[4];
  buf[0] = 'R'; // For a character array to qualify as a string, need a null character.  
  buf[1] = 0;   // '\0' same _value_ as 0  
  str[3] = buf; // array buf converts to address of first element: char *

  str[4] = NULL; // Do not want to print this.

  for (int i = 0; str[i]; i++)
    puts(str[i]);
  return 0;
}

Hello  
Earth  
How  
R  
value[0] = "hello";

這怎么能舉行“你好”。 它只能容納一個字符。

同樣, value[5]不足以實現此目的。 '\\0'將沒有空格,並且程序將顯示UB

因此,要么使用value[6] -

char value[6];
strncpy(value,"hello",sizeof value);

或者這樣聲明-

char value[]="hello";

然后將指針指向此數組。 像這樣的東西

str[0]=value;

暫無
暫無

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

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