c - 使用 strcpy 更新结构中的 char[] 字段。 C中的指针问题

标签 c

我想知道如何使用文件中的标记行设置结构的字符串值。基本上我正在阅读像 "Person 100 100" (由 \t 分隔)这样的行,我需要使用返回的内容设置结构的字符串值。

错误消息:

||In function 'main':|
|32|warning: passing argument 1 of 'strcpy' from incompatible pointer type|
c:\program files (x86)\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\..\..\..\..\include\string.h|45|note: expected 'char *' but argument is of type 'char **'|
||=== Build finished: 0 errors, 1 warnings ===|

代码片段:

char buffer[20];
fgets(buffer, 20, file);

while (*buffer != EOF)
{
    struct student temp;
    char *result = NULL;
    //set name
    strcpy(temp.name,strtok(buffer,"\t"));
    //set midterm
    result = strtok(NULL, "\t");
    temp.midterm = atoi(result);
    //set final
    result = strtok(NULL, "\t");
    temp.final = atoi(result);
}

最佳答案

strcpy函数定义如下:

char *strcpy(char *restrict s1, const char *restrict s2);

不知道student结构,所以第一个参数可能传递参数错误。下面的代码就可以了:

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

struct student
{
    char name[128];
    int midterm;
    int final;
};

char buffer[] = {"Person    100 100"};
//fgets(buffer, 20, file);

int main()
{
    //while (*buffer != EOF)
    {
        struct student temp;
        char *result = NULL;
        //set name
        strcpy(temp.name,strtok(buffer,"\t"));
        //set midterm
        result = strtok(NULL, "\t");
        temp.midterm = atoi(result);
        //set final
        result = strtok(NULL, "\t");
        temp.final = atoi(result);
        printf("name = %s, midterm = %d, final = %d\n", temp.name, temp.midterm, temp.final);
    }

    return 0;
}

关于c - 使用 strcpy 更新结构中的 char[] 字段。 C中的指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10627968/

相关文章:

c - c中整数到 float 的隐式转换

C - 循环中的 rand()

c - 链接列表 - 全局变量与局部变量

java - JNI + 类型转换(例如,Signed Short 到 Unsigned Short)

c - 将一个字符串附加到 C 中的另一个字符串,不带任何空格

将二维数组中的每个字符串复制到一维数组中

c - 如何更改返回局部变量的函数

c - "Size in TCHARs"是什么意思?

c - 为什么在循环内,带有 %d 的 scanf() 不等待用户输入,以防它之前收到无效输入?

c - 堆叠在数据结构中