在 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/