指针数组的有关问题,请高人帮帮忙
指针数组的问题,请高人帮帮忙
#include <stdio.h>
#include <iostream>
char * f1( )
{
char *ptr[2];
ptr[0]=new char[10];
ptr[1]=new char[10];
strcpy(ptr[0], "hello ");
strcpy(ptr[1], "make ");
return *ptr;
}
void main()
{ int i;
char *p[2];
*p= f1();
for(i=0;i <2;i++)
printf( "%s\t ",p[i]);
}
我写这个函数的作用就是在函数内部给指针数组给赋值,然后在主函数中输出。但是调试后只能输出hello,另一个就是内存错误!我知道可能是函数只返回了ptr[0]的地址。ptr[1]没有返回。但是怎么样才能实现我做的功能那?
函数不需要形参。如果用形参我自己已经可以实现了。我做的程序必须要没有形参并且返回一个指针。也就是说函数声明只能是char * f(),我想了半天还是琢磨不出来
大家帮帮忙吧
------解决方案--------------------
#include <stdio.h>
#include <iostream>
using namespace std;
char **f1( )
{
char **ptr = new char*[2];
ptr[0]=new char[10];
ptr[1]=new char[10];
strcpy(ptr[0], "hello ");
strcpy(ptr[1], "make ");
return ptr;
}
void main()
{ int i;
char **p;
p = f1();
for(i=0;i <2;i++)
printf( "%s\t ",*(p+i));
system( "pause ");
delete []*p;
delete []*(p+1);
}
#include <stdio.h>
#include <iostream>
char * f1( )
{
char *ptr[2];
ptr[0]=new char[10];
ptr[1]=new char[10];
strcpy(ptr[0], "hello ");
strcpy(ptr[1], "make ");
return *ptr;
}
void main()
{ int i;
char *p[2];
*p= f1();
for(i=0;i <2;i++)
printf( "%s\t ",p[i]);
}
我写这个函数的作用就是在函数内部给指针数组给赋值,然后在主函数中输出。但是调试后只能输出hello,另一个就是内存错误!我知道可能是函数只返回了ptr[0]的地址。ptr[1]没有返回。但是怎么样才能实现我做的功能那?
函数不需要形参。如果用形参我自己已经可以实现了。我做的程序必须要没有形参并且返回一个指针。也就是说函数声明只能是char * f(),我想了半天还是琢磨不出来
大家帮帮忙吧
------解决方案--------------------
#include <stdio.h>
#include <iostream>
using namespace std;
char **f1( )
{
char **ptr = new char*[2];
ptr[0]=new char[10];
ptr[1]=new char[10];
strcpy(ptr[0], "hello ");
strcpy(ptr[1], "make ");
return ptr;
}
void main()
{ int i;
char **p;
p = f1();
for(i=0;i <2;i++)
printf( "%s\t ",*(p+i));
system( "pause ");
delete []*p;
delete []*(p+1);
}