Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
字符串实现和can';我似乎没有使用箭头操作符_C_Pointers_Structure - Fatal编程技术网

字符串实现和can';我似乎没有使用箭头操作符

字符串实现和can';我似乎没有使用箭头操作符,c,pointers,structure,C,Pointers,Structure,我应该为字符串实现编写一个模块,我大致知道如何以及从哪里开始。但每次我尝试在C中使用箭头操作符时,都会出现一个错误 SET-应该分配内存并用输入初始化字符串。 复制-复制将一个字符串复制到另一个字符串 CONCAT串联 打印-最后打印出来 因此,任何帮助都将不胜感激: 头文件: #ifndef string_h #define string_h typedef struct { int len; char *s; } string_t;

我应该为字符串实现编写一个模块,我大致知道如何以及从哪里开始。但每次我尝试在C中使用箭头操作符时,都会出现一个错误

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

因此,任何帮助都将不胜感激:

头文件:

    #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) {

    }
#包括“string.h”
#包括
#包括
无效集(字符串*s1,字符*s){
s1=(字符串*)malloc(sizeof(字符串));
如果(s==NULL){
s1->len=0;
}否则{
s1->len=strlen(s);
s1=(字符串*)malloc(sizeof(s1->len));
s1->s=s;
}
}
无效副本(字符串*s1,字符串s2){
}
void concat(字符串*s1,字符串s2){
}
无效打印(字符串s1){
}

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

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


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

是,这是我的想法,但我不知道如何在不更改头文件的情况下在实现中修复/使用它。@dean\u winchester刚刚在答案中给出了提示。谢谢,我刚刚看到了!但我不知道我是否被允许更改参数和头文件,因为这是教授给我们的。所以我想知道是否有其他方法可以在不更改头文件的情况下解决它。@dean_winchester:只需在实现中使用
string
,而不是
string*
。根本不需要更改头文件。@MarkBenningfield是的,但由于过程是在headerfile中声明的,所以我也必须在那里更改它的参数。因为
set()
s1
参数实际上是指向
字符串的指针(这是您需要的,所以这很好),您需要在
malloc()
行中取消对它的引用。您需要设置它指向分配的内存地址的内容,并为
字符串而不是
字符串分配空间:
*s1=malloc(sizeof(string))
我刚刚做了,但它仍然没有解决“s1->len”错误。这里也有引用:
(*s1)->len
或者在函数中使用本地
字符串tmp
而不是
s1
,然后在返回之前设置
*s1=tmp
。非常感谢!!成功了!还有一个问题。我是否也必须在if语句中取消引用它?我的意思是:(*s1)=malloc(sizeof((*s1)->len));