gpt4 book ai didi

c - 将数据添加到结构内部的数组

转载 作者:太空宇宙 更新时间:2023-11-04 03:48:49 26 4
gpt4 key购买 nike

如何将数据设置为 3 行的数组同时具有 4 个元素的数组?

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

typedef struct
{
char value[6];
} MyType;

typedef struct
{
int size;
MyType *values;
} NewType;

static NewType car;
static MyType mytype = {{'\0'}};

void Init(NewType *car)
{
car->size = 3; // Will contain 3 rows of 4 elements
car->values = (MyType*) calloc(car->size,sizeof(MyType));
}

// Get data into
void Write(NewType *car, MyType *data)
{
strcpy(car->values[0].value, data[0].value); // ** Here is where complains

printf("%d\n", car->values[0]); // Printing wrong data!
}

int main()
{
Init(&car);

strcpy(mytype.value, "Hello");

Write(&car, &mytype);

system("PAUSE");
}

最佳答案

在这段代码 strcpy(mytype.value, "Hello"); 中,您将一个 5 个字母的字符串复制到一个 4 个字符的数组中,这是非法的,因此这可能会导致错误。将您复制到 mytype.value 的字符串更改为更短的字符串(如 "Bye")或增加 value 中的元素数量char 数组到您要放入其中的单词的字符数加上一个终止空字符。

另外 Write() 函数中的 printf() 语句有一个格式字符串,指示打印一个 int,我对此表示怀疑是你真正想要的。以下是重写的Write()main()函数。

void Write(NewType *car, MyType *data)
{
strcpy(car->values[0].value, data->value);

printf("%s\n", car->values[0].value);
}

int main()
{
Init(&car);

strcpy(mytype.value, "Bye");

Write(&car, &mytype);

system("PAUSE");
}

关于c - 将数据添加到结构内部的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22277690/

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