【问题标题】:Add data to array inside struct将数据添加到结构内的数组
【发布时间】:2014-03-09 02:29:15
【问题描述】:

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

【问题讨论】:

  • 您希望printf 显示什么?如果你把它改成printf("%s\n", car-&gt;values[0].value);,那么它将打印Hello
  • "Hello" 需要 6 个数组而不是 4 个数组。

标签: c arrays visual-studio-2010 struct


【解决方案1】:

在这段代码 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");
}

【讨论】:

  • @valter 你是对的,因为values 是一个指针,所以-&gt; 也可以工作,但是values 指针被认为是一个值的集合,两个表达式是等价的(@ 987654334@、(values + 1)-&gt;value = values[1].value 等等)所以在这种情况下这只是一个偏好问题。
  • 当然可以! (*values).value 与 values->value 相同。傻我。
【解决方案2】:

在您的printf("%d\n", car-&gt;values[0]) 中,您实际上是在尝试打印您在Init() 中调用的内存的前4 个字节,格式为带符号的十进制整数。 (在 x86 的情况下为 4。一般为 sizeof(int))。

要打印该值,您应该:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 2021-02-02
    相关资源
    最近更新 更多