首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

struct数组的有关问题

2013-12-11 
struct数组的问题定义结构体后,再用结构体+数组的话,数组的size值必须是个具体的数吗?以下是代码:#include

struct数组的问题
定义结构体后,再用结构体+数组的话,数组的size值必须是个具体的数吗?以下是代码:
#include <cstdlib>
#include <iostream>

using namespace std;
struct Person
{
       char name[30];
       char surname[40];
       int age;
       
};
void scan(struct Person *p)
{
    printf("Give a name:");
    scanf("%s",&(p->name)); 
    printf("Give a surname;");
    scanf("%s",&(p->surname)); 
    printf("Give a age;");
    scanf("%i",&(p->age));
     }
void print(struct Person p)
{
    printf("Name:%s\n",p.name); 
    printf("Name:%s\n",p.surname);
    printf("Name:%i\n",p.age);
     } 
void scanTab(struct Person *tab,int size)
{
    for(int i=0;i<size;i++)
    scan(&tab[i]); 

    
     }     
void printTab(struct Person *tab,int size)
{
    for(int i=0;i<size;i++)
 
    print(tab[i]);
    printf("\n");
    
     }          
int main(int argc, char *argv[])
{
    int n;
    printf("please give me a size:");
    scanf("%i",&n);
    struct Person table[n];
    scanTab(table,n);
    printTab(table,n);
    system("PAUSE");
    return EXIT_SUCCESS;
}
提示的错误在这一行: struct Person table[n];
但是这个代码在DEV-C++上运行的挺好,但是在vsual c++上运行的时候就出错误了.
错误提示:
D:\Microsoft Visual Studio\MyProjects\test.cpp(47) : error C2057: expected constant expression
D:\Microsoft Visual Studio\MyProjects\test.cpp(47) : error C2466: cannot allocate an array of constant size 0
D:\Microsoft Visual Studio\MyProjects\test.cpp(47) : error C2133: 'table' : unknown size
看了半天,也不知道改哪!大家帮忙看看错哪了?
[解决办法]

引用:

 struct Person table[n];
//改成
struct Person *ptable = ( struct Person *)malloc(sizeof( struct Person) * n);

调试一下,还是不行,而且同样的两次运行,提示错误竟然不一样!

    struct Person *p table = ( struct Person *)malloc(sizeof( struct Person) * n);
    scanTab(table,n);
    printTab(table,n);
    system("PAUSE");
    return EXIT_SUCCESS;

D:\Microsoft Visual Studio\MyProjects\test.cpp(47) : error C2146: syntax error : missing ';' before identifier 'table'
D:\Microsoft Visual Studio\MyProjects\test.cpp(47) : error C2065: 'table' : undeclared identifier
D:\Microsoft Visual Studio\MyProjects\test.cpp(47) : error C2440: '=' : cannot convert from 'struct Person *' to 'int'



//改成这样吧, 楼主基础不太好!找本c语言基础书籍看看先吧!
    struct Person *ptable = ( struct Person *)malloc(sizeof( struct Person) * n);
    scanTab(ptable,n);
    printTab(ptable,n);
    system("PAUSE");
    return EXIT_SUCCESS;

热点排行