【问题标题】:incompatible types in assignment of char * to char[200]将 char * 分配给 char[200] 时的类型不兼容
【发布时间】:2023-03-26 10:30:01
【问题描述】:

执行main,它会要求输入。

将输入存储在 argbuf 中。

然后,使用 strwrd 将 argbuf 拆分为标记

但是,它显示“错误:将 char * 分配给 char[200] 时类型不兼容”

我不知道为什么..

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char argbuf[200];//used to store input

char *strwrd(char *s, char *buf, size_t len, char *delim){
    s += strcspn(s, delim);
    int n = strcspn(s, delim); /* count the span (spn) of bytes in */
    if (len-1 < n)             /* the complement (c) of *delim */
        n = len-1;
    memcpy(buf, s, n);
    buf[n] = 0;
    s += n;
    return (*s == 0) ? NULL : s;
}



int main(){
    fgets(argbuf, sizeof(argbuf), stdin);
    char token[10][20];
    int index;
    for (index = 0; index < 10; index++) {
        argbuf = strwrd(argbuf, token[index], sizeof(token[index]), " \t");
        if (argbuf == NULL)
            break;
    }
    return 1;
}

【问题讨论】:

标签: c split


【解决方案1】:

strwrd 返回char*,因此您不能将此值存储在char[200] 变量中。请改用char* 类型。

【讨论】:

  • 我认为“argbuf”代表argbuf[200]的地址?
  • 您已将 argbuf 声明为数组,因此有时将其视为 char* 是合适的。但是在这里,您不能将 char* 返回到 argbuf,因为它在内存中是不可移动的。
  • 我声明了另一个指针“char *buf=NULL”。并将数组的地址分配给 buf "buf=argbuf"。然后,使用 buf 作为 strwrd 的参数。最后,它起作用了。
【解决方案2】:

char *char[x]是不同的类型,见here

Here's another good resource

在您的代码中char argbuf[200]; 是一个静态分配的数组,因此您不能为其分配指针。为什么要来回传递全局?如果您打算将 argbuf 用作全局变量,那么如果您的 each for '\t' 返回有效的值,则直接在 strwrd 中修改它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    相关资源
    最近更新 更多