问题描述
我正在学习C并且有一个问题:malloc()。
我写了一个简单的程序,它为一个结构赋值然后
打印如下:
#include< stdio.h>
#include< stdlib.h>
struct item {
char name [20];
int quantity;
};
int main(int argc,char * argv [])
{
struct item * stuff;
/ /为结构分配内存
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);
免费(东西);
返回0;
}
然后我改变结构d eclaration以动态
为char数组分配内存
:
struct item {
char * name ;
int数量;
};
程序编译没有错误,但它崩溃了以下
错误:
第3行:2485分段错误
感谢您的帮助
不确定是否重要,我的电脑如下:
Linux Slackware 10.1
使用gcc -o test struct.c编译程序
还有其他人能够运行吗?
st尚未定义。你可能意味着东西[1] .quantity
stuff [2] .quantity
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 {
charname[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
Not sure it matters, my PC is as follows:
Linux Slackware 10.1
compiling program with "gcc -o test struct.c"
Is anyone else able to run this ?
st has not been defined. You probably mean stuff[1].quantity
stuff[2].quantity
In the first case the struct contains memory (20 bytes) for storing the
names so the malloc() for the structs is sufficient. In the second
case the struct contains only a pointer, so you are copying "apple" to
whatever random address ends up in stuff[1].name. Undefined behaviour.[*]
You could either use malloc() to allocate space for storing the name
and assign the resulting pointer to stuff[1].name, or just do
stuff[1].name = "apple";
and not copy the string at all.
In this case just assigning the pointer would make more sense, but in a
real example either strategy might be appropriate.
-thomas
[*] Technically the undefined behaviour could be even worse than
copying to some random address, but that''s bad enough.
这篇关于寻找malloc()的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!