【发布时间】:2015-01-31 19:08:26
【问题描述】:
有什么方法可以在运行时分配准确足够的空间而不询问字符串的长度?
int main()
{
char **tests;
int counter;
int i;
int j;
int testCases;
scanf(" %d", &testCases);
tests = malloc(sizeof(char *) * testCases);
for(i = 0; i < testCases; i++)
//stuck here, normally I would put tests[i] = malloc(length_of_string)
//but I don't know the length of string until runtime
}
【问题讨论】:
-
除非文件输入是一个选项,我不知道
-
@juice 有什么问题?如果您不知道长度,请使用 strlen 函数找出它,这对我来说似乎很容易,所以我怀疑是否正确解释了您的问题。您能否添加信息如何获取字符串?
-
@juice 字符串不是以空结尾还是什么?
-
使用
int main (int arc, char **argv )将#testcases作为输入参数并使用strnlen()获取输入的长度。
标签: c char runtime c-strings dynamic-allocation