S
SP
I am learning C and have a question re: malloc().
I wrote simple program which assigns a value to a structure and then
prints it as follow:
#include <stdio.h>
#include <stdlib.h>
struct item {
char name[20];
int quantity;
};
int main (int argc, char *argv[])
{
struct item *stuff;
//allocate memory for structure
stuff = malloc(3 * sizeof(struct item));
strcpy(stuff[1].name, "apple");
stuff[1].quantity = 1;
strcpy(stuff[2].name, "banana");
stuff[2].quantity = 2;
printf("%s %d\n", stuff[1].name, st.quantity);
printf("%s %d\n", stuff[2].name, st.quantity);
free(stuff);
return 0;
}
I then change the structure declaration in order to dynamically
allocate memory
for the char array:
struct item {
char *name;
int quantity;
};
The program compiles with no errors, but it crashes with the following
error:
line 3: 2485 Segmentation fault
Thanks for your help
I wrote simple program which assigns a value to a structure and then
prints it as follow:
#include <stdio.h>
#include <stdlib.h>
struct item {
char name[20];
int quantity;
};
int main (int argc, char *argv[])
{
struct item *stuff;
//allocate memory for structure
stuff = malloc(3 * sizeof(struct item));
strcpy(stuff[1].name, "apple");
stuff[1].quantity = 1;
strcpy(stuff[2].name, "banana");
stuff[2].quantity = 2;
printf("%s %d\n", stuff[1].name, st.quantity);
printf("%s %d\n", stuff[2].name, st.quantity);
free(stuff);
return 0;
}
I then change the structure declaration in order to dynamically
allocate memory
for the char array:
struct item {
char *name;
int quantity;
};
The program compiles with no errors, but it crashes with the following
error:
line 3: 2485 Segmentation fault
Thanks for your help