用变量定义结构体数组
int n;scanf("%d",&n);
struct info{
char name;
char number;
int grade;
};
struct info a;
最后一行的代码会报错,如何用n达到定义结构体数组的效果 int n;
struct info{
char name;
char number;
int grade;
}*a;
printf("输入数组大小:\n");
scanf("%d",&n);
a=(struct info *)malloc(n*sizeof(struct info));
strcpy((a+1)->name,"aaa"); //访问a
strcpy((a+1)->name,"bbb");
(a+1)->grade=1;
printf("name:%s\n",(a+1)->name); //访问a
printf("grade:%d\n,(a+1)->grade");
如果是c++,可以使用new。 本帖最后由 bin554385863 于 2019-9-14 19:44 编辑
#include <stdio.h>
struct num
{
char x;
int y;
};
int main(int argc, char const *argv[])
{
int n = 5;
struct num arr;
for (size_t i = 0; i < n; i++)
{
arr.x = 'a' + i;
arr.y = i;
}
for (size_t i = 0; i < n; i++)
{
printf("arr[%d](%c , %d)\n", i, arr.x, arr.y);
}
return 0;
}
----------------------------------------------------------------------------
Microsoft Windows [版本 10.0.16299.1087]
(c) 2017 Microsoft Corporation。保留所有权利。
E:\Users\86184\Documents\Code>c:\Users\86184\.vscode\extensions\ms-vscode.cpptools-0.25.1\debugAdapters\bin\WindowsDebugLauncher.exe --stdin=Microsoft-MIEngine-In-bjxofrn1.njt --stdout=Microsoft-MIEngine-Out-cgeou2vr.qnc --stderr=Microsoft-MIEngine-Error-sgfv4nd4.pd4 --pid=Microsoft-MIEngine-Pid-oh4l2mo1.nx0 "--dbgExe=E:\My Program\MinGW\bin\gdb.exe" --interpreter=mi
arr(a , 0)
arr(b , 1)
arr(c , 2)
arr(d , 3)
arr(e , 4)
E:\Users\86184\Documents\Code>
----------------------------------------------------------------------
或者
C++
#include <iostream>
struct num
{
char x;
int y;
};
int main(int argc, char const *argv[])
{
int n = 5;
struct num arr;
for (size_t i = 0; i < n; i++)
{
std::cin>>arr.x>>arr.y;
}
for (size_t i = 0; i < n; i++)
{
printf("arr[%d](%c , %d)\n", i, arr.x, arr.y);
}
return 0;
}
--------------------------------------------------------------------------------------------
E:\Users\86184\Documents\Code>c:\Users\86184\.vscode\extensions\ms-vscode.cpptools-0.25.1\debugAdapters\bin\WindowsDebugLauncher.exe --stdin=Microsoft-MIEngine-In-vzsyujsh.jnr --stdout=Microsoft-MIEngine-Out-kb0qq0kz.jbs --stderr=Microsoft-MIEngine-Error-flz0k4io.1jy --pid=Microsoft-MIEngine-Pid-tgdlmxgw.1yi "--dbgExe=E:\My Program\MinGW\bin\gdb.exe" --interpreter=mi
a 2
b 6
v 9
r 9
l 4
arr(a , 2)
arr(b , 6)
arr(v , 9)
arr(r , 9)
arr(l , 4)
E:\Users\86184\Documents\Code>
页:
[1]