簡體   English   中英

在c中打印未知的2D數組

[英]printing a unknown 2D array in c

我是stackoverflow的新手。

我有一個像這樣的未知大小的2D字符串數組。

   char **table = NULL;
   table = myfunc();   // Table now contains something like {"Merry","Leo","Linus"...} 

有沒有辦法用這樣的循環打印這個數組?

   int i = 0;
   while(????){   // Is there a condition i can use here to loop the list? 
        printf("%s", table[i]);
        i++;
   }

所以我得到下面的輸出。

Merry
Leo
Linus

提前致謝。

沒有

其他選擇:

  1. 將變量的地址傳遞給函數,並將其設置為函數中數組中的元素數:

     char **table = NULL; size_t n; table = myfunc(&n); 

    然后,條件可能是:

     while(i < n) { … } 
  2. 用一些特殊值標記數組的結尾,比如NULL

     char **table = NULL; table = myfunc(); // Table now contains something like {"Merry","Leo","Linus", …, NULL} 

    然后,條件可能是:

     while(table[i]) { … } 

注意:在這兩種選擇中,不要忘記讓i成為size_t

你可以使用哨兵。 修改myfunc以在最后一個元素后添加NULL 你的數組看起來像{"Merry", "Leo", ...., NULL}

現在,您可以像這樣迭代:

int i = 0;

while (table[i] != NULL)
{
    printf("%s", table[i]);
    i++;
}

小心,使用基於哨兵的解決方案,你可能會遇到一些麻煩,比如字符串:你確定哨兵是否正確設置, 數據源是否安全? 如果沒有,我建議你添加一個限制: while(i < MAX && table[i] != NULL)

您可以在函數main中使用C標准使用的模型。

主要的標准聲明是

int main( int argc, char * argv[] )
{
   //...
}

argv[argc]始終等於NULL。 使用此事實,您可以通過以下方式輸出main的所有參數

#include <stdio.h>

int main( int argc, char * argv[] )
{
    while ( *argv ) puts( *argv++ );
}

所以你的程序需要的是字符串數組的最后一個元素等於NULL

在這種情況下,你可以寫

   char **table = NULL;
   table = myfunc();

   for ( char **p = table; *p; ++p ) puts( *p );

另一種方法是編寫函數,使其也報告數組中的元素數量。 在這種情況下,函數可以聲明為

size_t myFunc( char ***table );

或者喜歡

char ** myFunc( size_t *n );

並稱之為

size_t n = myFunc( &table );

要么

size_t n;

table = myFunc( &n );

暫無
暫無

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

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