C 创建一个字符串结构

标签 c string struct segmentation-fault

所以,我一直致力于为字符串实现这个结构。但是,我在调用 *createString(); 时不断遇到段错误;

这里是.h内容

typedef struct {
    char *characters;
    int length;
} String;

String *createString();

这是我的 .c 文件中的实现

String *createString(){
    char *m,b;
    int n = 0;
    String *theS = (String *) malloc (sizeof(String));
    m = theS->characters;
    b = getchar();
    while((b = getchar()) != '\n'){
        *(m+n) = b;
        n++;
        m = realloc(m, n+1);
    }
    *(m+n) = '\0';
    theS->length = strlen(theS->characters);
    return new;
}

最佳答案

问题1

Q:在这一行之后:

String *theS = (String *) malloc (sizeof(String));

theS->characters 指向什么?

A:谁知道呢?但是没有任何用处。

您至少需要分配一个字符,以保存最终插入的 '\0'

String *theS = malloc (sizeof(String));
theS->characters = malloc(1);

问题2

然后你在整个地方修改 m,但永远不要将该值重新分配给 theS->characters,所以当你说

theS->length = strlen(theS->characters);

这不会是一个很有帮助的答案。

在该行之前,添加:

theS->characters = m;

问题3

return new;

应该是:

return theS;

问题4

您正在丢弃第一个字符。只需删除独立的 b = getchar(); 行。

工作示例:

https://ideone.com/tm1TG9

关于C 创建一个字符串结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28752121/

相关文章:

c++ - 消息框中的字符串自动换行?

c - 生成没有指针的大写字母

ios - 如何使用 Swift 在文本字段(从右到左)输入货币格式?

c - 错误: initializer element is not constant - linux driver

c - C中的数据封装

c - 如何在 Linux 中使用 x-window lib 使图像变暗

c - 如何在没有安装cmake的机器上使用cmake

Matlab:结构中变量的名称

c - StatusBar 是默认以简单模式创建的吗?

c# - 如何更改c#中窗口窗体的原点即左上角和openGL C即中心?