c - 用 char *p 定义字符串是正确的;然后再赋值?

标签 c string pointers dynamic

我想在不知道它的确切维度的情况下创建一个字符串,这是正确的还是会有不可预测的行为?

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/

相关文章:

c - Linux 控制台键盘处理程序

C - 增量不更新变量值

c - C中的Web服务器问题

regex - 在 Perl 中打印没有子字符串的字符串

使用函数的 C++ 字符串输入

arrays - 从字符串中逐字抓取字符

C 在给定时间范围后运行脚本,同时游戏仍然可以玩(不是延迟)

c - 我想访问指针数组的值并对其求和,但得到了错误的值

c++ - 在其他指针中删除其对象后检查指针是否为 NULL

c - 为之前初始化为 NULL 的指针赋值