繁体   English   中英

向结构内的数组添加数据

[英]Add data to array inside struct

如何将数据设置为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");
}

实际上printf("%d\\n", car->values[0])在您的printf("%d\\n", car->values[0])您尝试打印Init()已调用的内存的前4个字节,格式为带符号的十进制整数。 (对于x86,通常为sizeof(int) )。

要打印值,您应该:

printf("%s\n", car->values->value); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM