结构体数组的动态值?
typedef struct What_if
{
char price[2];
} what_if ;
what_if *what_if_var;
int main(int argc,int argv[])
{
int m= argv[1];
what_if_var[m]='\0';
format_input_records();
getch();
return 0;
}
int format_input_records()
{
strcpy(what_if_var[0].price,"sss") ;
printf("\ntrans_Indicator ==== : : %s",what_if_var[0].price);
return 0;
}
这里我需要结构数组大小的动态值?我怎样才能实现这个请帮助我?
typedef struct What_if
{
char price[2];
} what_if ;
what_if *what_if_var;
int main(int argc,int argv[])
{
int m= argv[1];
what_if_var[m]='\0';
format_input_records();
getch();
return 0;
}
int format_input_records()
{
strcpy(what_if_var[0].price,"sss") ;
printf("\ntrans_Indicator ==== : : %s",what_if_var[0].price);
return 0;
}
here i need dynamic value for structure array size ?how can i achieve this plz help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,你有一个问题,我认为你不明白指针是什么:
你创建了一个指向
What_if
结构的指针,从不分配任何东西,然后尝试使用它(并作为数组其中)您也没有
main()
的正确签名正如对您的问题的直接评论所述,这表明您确实不了解话
虽这么说,您需要的是一个结构数组,其大小通过 argv 传入(从 char 转换之后) * 到 int),并且在结构内部您需要有一个 char * 指针。对于要存储的每个内容,您需要使用
malloc()
或使用strdup()
,然后将其分配给结构中的指针。First, you have a problem in that I don't think you understand what a pointer is:
You created a pointer to a
What_if
struct, never allocate anything, then try and use it (and as an array of them)You also don't have the correct signature for
main()
As noted by a direct comment to your question, this is an indication that you really don't understand the basics of the language, and an introductory book is in order.
That being said, what you need is an array of your structs the size of which is passed in via
argv
(after converting it from char* to int), and inside the struct you'd need to have achar *
pointer. For each thing you want to store, you will need tomalloc()
or usestrdup()
then assign it to the pointer in your struct.定义 :
您可以在您的结构中 。
当您知道要存储的字符的确切大小时初始化它:
You could define :
in your struct.
The initialize it when you know the exact size of chars to be stored:
您需要先通过调用
malloc()
来分配what_if_var
,然后才能对其进行分配。我还建议您避免使用全局变量。相反,将what_if_var
设置为本地。You need to allocate
what_if_var
with a call tomalloc()
before you can assign to it. I would also advise you to avoid using a global variable. Instead makewhat_if_var
local.