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

malloc的有关问题,太诡异了

2012-02-10 
malloc的问题,太诡异了#includestdio.h#includestring.h#includestdlib.h#includectype.hvoidupca

malloc的问题,太诡异了
#include   <stdio.h>
#include   <string.h>
#include   <stdlib.h>
#include   <ctype.h>

void   upcase(char   *oldstr,   char   *newstr);

int   main(void)
{
char   *string   =   NULL;

upcase( "Hello ",   string);
printf( "str1=%s   \n ",   string);
free(string);

upcase( "Goodbye ",   string);
printf( "str2=%s\n ",   string);
free(string);

return   0;
}

void   upcase(char   *oldstr,   char   *newstr)
{
int   i;

newstr   =   malloc(strlen(oldstr)   +   1);
strcpy(newstr,   oldstr);
printf( "%s\n ",newstr);

for   (i   =   0;   i   <   strlen(newstr);   i++)
{
newstr[i]   =   toupper(newstr[i]);
}
return;
}
            执行结果是:
Hello
str1=(null)  
Goodbye
str2=(null)
          为什么是这样子?


[解决办法]
当然了,str在你这里永远都为null
[解决办法]
晕,函数
void upcase(char *oldstr, char *newstr)
中oldstr,newstr都是传入函数的参数(形参)
但你在函数中确
newstr = malloc(strlen(oldstr) + 1);
用malloc给形参分配空间,实在是不知道该怎么说好了!
另外strcpy的使用要注意
函数没有返回值,但确使用了return
总之,这个函数问题很多

代码等下贴上了!
[解决办法]
你上次发的这个帖子的问题弄清楚了没有?http://community.csdn.net/Expert/topic/5750/5750772.xml?temp=.4806787
[解决办法]
要么改成双重指针
或者char * upcase(char *oldstr, char *newstr);
return newstr;

char * upcase(char *oldstr, char *newstr);

int main(void)
{
char *string = NULL;

string = upcase( "Hello ", string);
printf( "str1=%s \n ", string);
free(string);

upcase( "Goodbye ", string);
printf( "str2=%s\n ", string);
free(string);

return 0;
}

char * upcase(char *oldstr, char *newstr)
{
int i;

newstr = malloc(strlen(oldstr) + 1);
strcpy(newstr, oldstr);
printf( "%s\n ",newstr);

for (i = 0; i < strlen(newstr); i++)
{
newstr[i] = toupper(newstr[i]);
}
return newstr;
}

热点排行