【问题标题】:Error using C string and arrays使用 C 字符串和数组时出错
【发布时间】:2015-03-10 17:02:14
【问题描述】:

这个问题我需要帮助,我似乎无法解决它。 我不断收到此错误

error: incompatible types when assigning to type ‘char[21]’ from type ‘char *’
       WordList[i].word = token;

代码

#include <stdio.h>
#include <string.h>

struct myWord{
    char word[21];
    int Length;
};

int main(){
    struct myWord WordList[20];
    char myString[] = "the cat in the hat jumped over the lazy fox";
    char *token;
    int i;

    while((token = strtok(myString, " ")) != NULL){
        for(i=0; i<20; i++){
            WordList[i].word = token;
            WordList[i].Length = strlen(token);
        }
    }
    for(i=0; i<20; i++)
        printf("%s\t%d\n", WordList[i].word, WordList[i].Length);

}

【问题讨论】:

  • 我投票结束这个问题,因为“请快速帮助”

标签: c arrays string struct


【解决方案1】:

数组没有复制赋值运算符。您必须自己将一个数组的每个元素复制到另一个数组中。对于字符数组,您可以使用标头 &lt;string.h&gt; 中声明的标准 C 函数 strcpy(或例如 strncpy

例如

#include <string.h>

//...

strcpy( WordList[i].word, token );

或者

#include <string.h>

//...

strncpy( WordList[i].word, token, sizeof( WordList[i].word ) );
WordList[i].word[sizeof( WordList[i].word ) - 1] = '\0';

考虑到这段代码是sn-p

while((token = strtok(myString, " ")) != NULL){
    for(i=0; i<20; i++){
        WordList[i].word = token;
        WordList[i].Length = strlen(token);
    }
}

错了。可以这样改写

i = 0;
if ( (token = strtok(myString, " ") ) != NULL )
{
    do
    {
        strncpy( WordList[i].word, token, sizeof( WordList[i].word ) );
        WordList[i].word[sizeof( WordList[i].word ) - 1] = '\0';
        WordList[i].Length = strlen(token);
        ++i;
    } while ( (token = strtok( NULL , " ") ) != NULL );
}

【讨论】:

  • strcpy 不是最好的建议。这是一个安全漏洞。 +0 表示正确和乐于助人
  • strncpy 和/或检查字符串长度。
【解决方案2】:

正如弗拉德所指出的,你不能以这种方式复制到数组,另一个问题是你没有正确使用strtok

strtok() 函数将一个字符串分解为一个零序列或 更多非空令牌。在第一次调用 strtok() 时,字符串 被解析的应该在str中指定。 在随后的每个调用中 应该解析相同的字符串,str必须为NULL

token = strtok(myString, " ")
while (token != NULL) {
    /* ... */
    token = strtok(NULL, " ");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-18
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多