簡體   English   中英

c字符串指針

[英]c string pointer

我開始學習C並且我對c字符串指針有點混淆。

int argc = 0;
const char *str[] = { "hello" , NULL, NULL };
str[argc++] = "nice!";
str[argc++] = "abc";
str[argc++] = "def"
send_args(argc, str); 
//the prototype/header : int send_args(int argc, const char **args);

因為send_args函數不修改傳遞的str的值,那些操作是否有效? 因為我不想做類似的事情:

int i, argc = 0;
char *str[3];
str[argc++] = strdup("nice!");
str[argc++] = strdup("abc");
str[argc++] = strduo("def)"
send_args(argc, str);
for (i = 0; i< argc; i++)
    if (str[i]) { free(str[i]); str[i]=NULL; }

先謝謝你們。

我看到第一個例子沒有錯。

是的,沒關系。 字符串文字可能放在初始化數據部分(細節是實現定義的),並且不需要(實際上甚至沒有可能)來釋放文字。 str的類型與send_args所需的類型兼容,所以一切都很好。

請注意,如上所述, str[]初始化為三個元素,因此不能容納四個或更多指針。 您可以通過聲明和初始化來實現相同的效果

const char *str[3];
str[0] = "nice!";
str[1] = "abc";
str[2] = "def"
send_args(3, str); 

是的,它們完全有效。 你需要關注argc因為你的增量超過了需要的數量。 只要你正確處理它就不會造成任何“不良影響”。 您可以在此處查看代碼示例

如果您詢問自動存儲持續時間,則在執行到達其創建的塊的末尾之前,不會銷毀您的str數組。

const char **fubar(void)
{
    int argc = 0;
    const char *str[] = { "hello" , NULL, NULL }; /* str is created here */
    str[argc++] = "nice!";
    str[argc++] = "abc";
    str[argc++] = "def"
    send_args(argc, str); /* the lifetime of str is still valid here */
    
  
 
  
  
  
    return str; 
   /* ... but str gets destroyed after this "return" statement */
}

int main(void) {
  
  
 
  
  
  
    const char **fubared = fubar(); 
  
  /* str has already been destroyed, and fubar's return value has been rendered garbage */
  /* so using fubared would be a bad idea. */
  return 0;
}

return導致str被銷毀,因為執行已超過它在其中創建的塊的末尾,並且返回的指針將指向垃圾。

在這種情況下,它們是有效的,因為字符串在編譯時靜態存儲,無法釋放。 它們的指針地址也不依賴於您所使用的功能。

但是如果你想使用一個本地的char數組來"nice!" ,它無效,因為send_args無法讀取其他函數的局部變量。

暫無
暫無

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

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