gpt4 book ai didi

c - C 中的结构问题

转载 作者:行者123 更新时间:2023-11-30 15:38:20 25 4
gpt4 key购买 nike

我的结构中有一个数组。我正在从文件读入字符串。我使用 strtok 获取前几个字符,并且我想将行的其余部分传递到结构中,最终传递到线程中。我收到以下错误:

从类型 char * 分配给类型 char[1024] 时,类型不兼容

引用下面的注释行。这可能与我尝试复制字符数组的方式有关,但我不确定更好的方法。

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <linux/input.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

typedef struct
{
int period; //stores the total period of the thread
int priority; // stores the priority
char pline[1024]; // stores entire line of text to be sorted in function.
}PeriodicThreadContents;

int main(int argc, char* argv[])
{
//opening file, and testing for success
//file must be in test folder
FILE *fp;
fp = fopen("../test/Input.txt", "r");

if (fp == NULL)
{
fprintf(stderr, "Can't open input file in.list!\n");
exit(1);
}

char line[1024];

fgets(line, sizeof(line), fp);

//getting first line of text, containing
char *task_count_read = strtok(line," /n");
char *duration_read = strtok(NULL, " /n");

//converting char's to integers
int task_count = atoi(task_count_read);

int i = 0;

PeriodicThreadContents pcontents;




printf("started threads \n");

while (i < task_count)
{
fgets(line, sizeof (line), fp);
strtok(line," ");

if (line[0] == 'P')
{
char *period_read = strtok(NULL, " ");
pcontents.period = atoi(period_read);
printf("%d",pcontents.period);
printf("\n");

char *priority_read = strtok(NULL, " ");
pcontents.priority = atoi(priority_read);
printf("%d",pcontents.priority);
printf("\n");

printf("\n%s",line);
memcpy(&(pcontents.pline[0]),&line,1024);
printf("%s",pcontents.pline);
}

}


return 0;
}

最佳答案

C 无法像其他语言那样处理字符串。如果不使用辅助函数,C 就没有字符串赋值或比较。

为了复制缓冲区中的字符串,您可以使用:

strcpy(pcontents.pline, line);

甚至(保证您的字符串不超过 1024 字节):

memcpy(pcontents.pline, line, 1024);
pcontents.pline[1023] = '\0';

对于其他字符串操作,请检查:http://www.gnu.org/software/libc/manual/html_node/String-and-Array-Utilities.html#String-and-Array-Utilities

关于c - C 中的结构问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21802569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com