我想在不知道它的确切维度的情况下创建一个字符串,这是正确的还是会有不可预测的行为?
char *p;
p="unknow string size";
如果这是错误的,我如何创建类似的东西,并用 string.h 函数修改它?
[edit]我又看了一遍答案,不是很清楚,我的第一个疑惑是: 这两个代码是否相等?
char *p="unknow string size"
和
char *p;
p="unknow string size";
最佳答案
C 中唯一的解决方案是使用realloc
函数
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *s = malloc(1);
printf("Enter a string: \t"); // It can be of any length
int c;
int i = 0;
while((c = getchar()) != '\n' && c != EOF)
{
s[i++] = c;
s = realloc(s, i+1);
}
s[i] = '\0';
printf("Entered string: \t%s", s);
free(s);
return 0;
}
are those two codes equals?
char *p="unknown string size"
and
char *p; p="unknown string size";
没有。第一个片段将 p
声明为指向 char
的指针,并将其初始化为指向字符串文字 “未知字符串大小”
。在第二个片段中,p
被定义为指向 char
的指针,然后对其进行赋值。
关于c - 用 char *p 定义字符串是正确的;然后再赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28138770/