c语言 - 赋值中的类型不兼容,为什么我不能这样做?



我有一个struct the_word,它具有变量char Word [word_length]

我有以下

typedef struct The_Word
{
    char word[WORD_LENGTH];
    int frequency;
    struct The_Word* next;
} The_Word;
int someFunc(char* word)
{
/*Rest of method excluded*/
struct The_Word *newWord = malloc(sizeof(struct The_Word));
newWord->word = word; // error here. How can I assign the struct's word to the pointer word
}

您需要使用strncpy复制字符串:

#include <string.h>
int someFunc(char* word)
{
  /*Rest of method excluded*/
  struct The_Word *newWord = malloc(sizeof(struct The_Word));
  strncpy(newWord->word, word, WORD_LENGTH);
  newWord->word[WORD_LENGTH - 1] = '';
}

您应该小心检查字符串是否适合数组中。就是这样,当参数char* word的长度长于WORD_LENGTH时。

您不会直接分配指针。相反,您应该使用strncpy()功能。

strncpy(newWord->word,word,strlen(word));

strcpy()memcpy()所有工作都类似。

typedef struct The_Word
{
    char word[WORD_LENGTH];
    int frequency;
    struct The_Word* next;
} The_Word;
int someFunc(char* word)
{
/*Rest of method excluded*/
  struct The_Word *newWord = malloc(sizeof(struct The_Word));
  memset(newWord->word,0,WORD_LENGTH);
  strcpy(newWord->word,word);
  /*return something*/
}

这给出了不兼容的类型错误,因为在C数组中被视为恒定指针。阵列和指针并非完全相同。尽管它们在大多数其他情况下的行为相同,但您不能重新分配数组指向的内容。

看起来您打算将字符串从函数参数复制到新分配的结构中。如果是这种情况,则如其他人建议使用strncpy()或memcpy()。

相关内容

最新更新