1

How can I set data into the array of 3 rows which at the same time has an array of 4 elements?

#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");
}
2
  • What do you expect the printf to show? If you change it to printf("%s\n", car->values[0].value);, then it will print Hello. Commented Mar 9, 2014 at 2:53
  • "Hello" needs array of 6 not 4. Commented Mar 9, 2014 at 2:57

2 Answers 2

1

In this piece of code strcpy(mytype.value, "Hello"); you are copying a 5 letters string into an array of 4 chars, which is illegal, so that might be causing the error. Either change the string you copy to mytype.value for a shorter one (like "Bye") or increase the number of elements in the value char array to the number of characters of the word you want to put in there plus one for the terminating null character.

Additionally the printf() statement in the Write() function has a format string that indicates to print an int, which I doubt is what you actually want. The following are the rewritten Write() and main() functions.

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

@valter You are correct in that values is a pointer so the -> would also work, but the values pointer is conceived as a collection of values and both expressions are equivalent (values->value = values[0].value, (values + 1)->value = values[1].value, and so on) so it's just a matter of preference in this case.
Yes of course! (*values).value is the same as values->value. silly me.
0

In your printf("%d\n", car->values[0]) you are actually trying to print the first 4 bytes of the memory you have calloced inside your Init(), formatted as a signed decimal integer. (4 in case of x86. sizeof(int) in general).

To print the value, you should:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.