将变量插入C中的指针数组的最有效方法

Seb*_*ler 2 c arrays pointers

在C中将变量插入指针数组(插入第二维)的最有效方法是什么?像这样:

    char * get_time(void)
    {
         time_t rawtime;
         struct tm * ptm;
         time (&rawtime);
         ptm = gmtime ( &rawtime );
         ptm->tm_hour = ptm->tm_hour - 4;
         return asctime(ptm);
    }

    char *some_array[] = {
        "some" get_time() "string",
        "some string"
    }
Run Code Online (Sandbox Code Playgroud)

Joh*_*ode 5

不幸的是,你无法在C中以这种方式连接字符串.你将不得不为最终字符串留出一些内存,写入它,并将该内存的位置分配给数组元素.这大概和它一样好:

/**
 * Set aside your array of pointers.  You can still initialize
 * array elements with string literals or NULL if you wish, like so
 */
char *some_array[] = {NULL, "some string", "another string", NULL ...}; 

/**
 * Alternately, you could use designated initializers
 *
 * char *some_array[] = {[1]="some string", [2]="another string", ... }
 *
 * to initialize some elements, and the other elements will be 
 * initialized to NULL. 
 */
...
char *timestr = get_time();   // get your time string

size_t bufLen = strlen( "some " ) + strlen( timestr ) + strlen( " string" ) + 1;
some_array[0] = malloc( bufLen * sizeof *some_array[0] ); // allocate memory for
                                                          // your formatted string 

if ( some_array[0] )
{
  sprintf( some_array[0], "some %s string", timestr );   // and write to it.
}
Run Code Online (Sandbox Code Playgroud)

编辑

请注意,在某些时候,您将需要使用以下free函数释放该内存:

free( some_array[0] );
Run Code Online (Sandbox Code Playgroud)

不幸的是,您必须跟踪分配内存的元素与您刚刚为其分配字符串文字的元素.尝试free使用字符串文字很可能会导致运行时错误.