注册 登录
编程论坛 C++教室

一个关于calloc的问题?

yxb0001 发布于 2009-09-23 11:24, 495 次点击
#include<iostream.h>
#include<stdlib.h>

int a[20]={2,0,6,23,41,0,5,6,0,99,33,22,0,12,67,0,9,3,6,23};
int *p,i,j=0;
int **y;
y=(int **)calloc(20,sizeof(int *));

int main()
{
    p=&a[0];
   
    for(i=0;i<20;i++)
    {
        if(*(p+i)!=0)
        {
            *(y+j)=p+i;
            
            cout<<**(y+j)<<" ";

            j++;
        }
    }
   
    return 0;
}

在此程序中为什么"y=(int **)calloc(20,sizeof(int *));"通不过?(vc6.0中)
4 回复
#2
gz812009-09-23 12:31
#include<iostream>
#include<stdlib.h>

int a[20]={2,0,6,23,41,0,5,6,0,99,33,22,0,12,67,0,9,3,6,23};
int *p,i,j=0;
int **y;

int main()
{
    y = (int **)calloc(20,sizeof(int *));

    p=&a[0];
     
    for(i=0;i<20;i++)
    {
        if(*(p+i)!=0)
        {
            *(y+j)=p+i;
            
            std::cout<<**(y+j)<<" ";

            j++;
        }
    }
     
    return 0;
}

[ 本帖最后由 gz81 于 2009-9-23 13:24 编辑 ]
#3
yxb00012009-09-23 12:44
还是通不过vc6.0,还是同样的错误。
error C2501: 'y' : missing storage-class or type specifiers
error C2040: 'y' : 'int' differs in levels of indirection from 'int ** 'error C2440: 'initializing' : cannot convert from 'int ** ' to 'int'

我的程序如果换一种写法,不使用calloc就可以运行,如:
int *b[20];

main ()中加一句:y=&*b[0];

可以得到正常的结果。但如果使用calloc就卡壳在上面地方。
#4
gz812009-09-23 13:20
以下是引用yxb0001在2009-9-23 12:44的发言:

还是通不过vc6.0,还是同样的错误。
error C2501: 'y' : missing storage-class or type specifiers
error C2040: 'y' : 'int' differs in levels of indirection from 'int ** 'error C2440: 'initializing' : cann ...

将y = (int **)calloc(20,sizeof(int *));这句放到main()里面

#include<iostream>
#include<stdlib.h>
 
int a[20]={2,0,6,23,41,0,5,6,0,99,33,22,0,12,67,0,9,3,6,23};
int *p,i,j=0;
int **y;
 
int main()
{
    y = (int **)calloc(20,sizeof(int *));

    p=&a[0];
     
    for(i=0;i<20;i++)
    {
        if(*(p+i)!=0)
        {
            *(y+j)=p+i;
            
            std::cout<<**(y+j)<<" ";
 
            j++;
        }
    }
     
    return 0;
}


[ 本帖最后由 gz81 于 2009-9-23 13:23 编辑 ]
#5
yxb00012009-09-23 13:37
动态分配需程序动起来才行。
1