【问题标题】:String implementation and can't seem to use the arrow operator字符串实现,似乎不能使用箭头运算符
【发布时间】:2021-03-28 09:25:46
【问题描述】:

我应该为字符串实现编写一个 Modul,我大概知道如何以及从哪里开始。但是每次尝试在 C 中使用箭头运算符时,我都会遇到错误。

SET - 应该分配内存并使用输入初始化字符串。 COPY - 复制将一个字符串复制到另一个 CONCAT - 连接 PRINT - 最后打印出来

所以任何帮助将不胜感激:

头文件:

    #ifndef string_h
    #define string_h

    typedef struct {
     int len;
     char *s;
    } string_t;

    typedef string_t *string;

    void set(string *s1, char *s);
    void copy(string *s1, string s2);
    void concat(string *s1, string s2);
    void print(string s1);


    #endif /* string_h */

实施文件:

    #include "string.h"
    #include <string.h>
    #include <stdlib.h>


    void set(string *s1, char *s) {
      s1 = (string*) malloc (sizeof(string));
 
      if(s == NULL) {
        s1 -> len = 0;
      } else {
        s1 -> len = strlen(s);
        s1 = (string*) malloc (sizeof(s1 -> len));
        s1 -> s = s;
      }

    }

    void copy (string *s1, string s2) {

    }

    void concat(string *s1, string s2) {

    }

    void print(string s1) {

    }

头文件看起来非常好,因为它没有太多功能。但是编译器每次都会给出“s1 -> len”的错误。因此,如果有人可以在这里帮助我,我将不胜感激,谢谢。

【问题讨论】:

  • 由于set()s1 参数实际上是指向string_t 的指针(这是您需要的,这很好),您需要在@987654326 中取消引用它@ 线。您需要将 它指向的内容 设置为您分配的内存地址,并为string_t 而不是string 分配空间:*s1 = malloc(sizeof(string_t));
  • 我刚做了,但仍然没有解决“s1 -> len”错误
  • 这里也取消引用:(*s1)-&gt;len
  • 或者在函数中使用本地的string tmp而不是s1,然后在返回之前设置*s1 = tmp
  • 非常感谢!!有效!还有一个问题。我是否也必须在 if 语句中取消引用它?我的意思是它会是这样的: (*s1) = malloc (sizeof((*s1) -> len));

标签: c pointers structure


【解决方案1】:

s1 似乎是指向指针的指针,而不是指向结构类型的指针。

您可以只更改typedef 以删除指针类型,或者只使用string 类型(不是string *),因为它本身已经是一个指针。

【讨论】:

  • 是的,这就是我的想法,但我不知道如何在我的实现中修复/使用它而不更改头文件..
  • @dean_winchester 刚刚在答案中给出了提示。
  • 谢谢,我刚看到!但是我什至不知道是否允许我更改参数和头文件,因为这是教授给我们的。所以我想知道是否有任何其他方法可以在不更改头文件的情况下解决它。
  • @dean_winchester:在实现中只使用string,而不是string*。根本不需要更改头文件。
  • @MarkBenningfield 是的,但是由于过程是在头文件中声明的,所以我也必须在那里更改它的参数。
猜你喜欢
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多