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

标签 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"
    }

最佳答案

不幸的是,你不能在 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.
}

编辑

请注意,在某些时候您会想要使用 free 函数释放该内存:

free( some_array[0] );

不幸的是,您必须跟踪为哪些元素分配了内存,以及为哪些元素分配了字符串文字。尝试释放字符串文字很可能会导致运行时错误。

关于c - 在C中将变量插入指针数组的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29783510/

相关文章:

c++ - 使用或不使用指针作为类引用。有什么不同?

c - C 字符串中 ptr、ptr[0] 和 &ptr[0] 的区别

c - 内存映射内核空间的解剖结构

C:rand()函数偶尔会导致Segmentation fault

c - 将标准输出重定向到文件描述符似乎不起作用,为什么?

arrays - C 数组的奇怪行为

c - pthread_cond_timedwait 忽略取消请求

c - C中安全获取字符串的方法

c - 为什么 puts() 函数会给我一个心形符号?

c - 免费如何知道要免费多少?