Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我想以精确的精度为输入时大小未知的输入字符串动态分配内存,即如果字符串是“堆栈”,我只想分配 6 个字节。
我想唯一的方法是根据输入继续增加数组的上限,但我无法弄清楚这段代码。
strdup()是你的朋友。
strdup()
char *p = strdup("stack");
您需要测量字符串的长度,然后进行分配。
长度:
int len = strlen(input_string);
分配内存
char *p = malloc (sizeof(char) * len + 1) ;
然后保存
strcpy (p, input_string);