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

正在学习c 指针传参这一块解决方法

2012-05-06 
正在学习c 指针传参这一块正在学习c 指针传参这一块, 我想动太申请3块内存,其中各存一个字符串,然后再动态

正在学习c 指针传参这一块
正在学习c 指针传参这一块, 我想动太申请3块内存,其中各存一个字符串
,然后再动态审请一块内在,长度为 3 * sizeof(char*),里面存这3块字符串对应的首地址,
然后将其通过传出参数传出。但是始终调不通,求高手帮忙 。

C/C++ code
#include <stdio.h>#include <stdlib.h>#include <malloc.h>#include <string.h>mc(char*** str){  char* s1=(char*)malloc(10);  char* s2=(char*)malloc(10);  char* s3=(char*)malloc(10);  char **ss,**p;  s1="hello";  s2="world";  s3="god";  /* printf ("%p,%p,%p\n",&s1,&s2,&s3); */  ss= (char**)calloc(3,sizeof(char*));  p=ss;  p= (&s1);  p++;  p= &s2;  p++;  p= &s3;  p++;  /* printf ("%p\n",p); */  *str=ss;}int main(int argc, char *argv[]){  char** str;  int i;  mc(&str);  printf ("%p\n",*str);  return 0;}


[解决办法]
试试看在子函数里面return一下,返回经过处理后的指针.
[解决办法]
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
mc(char*** str){
char* s1=(char*)malloc(10*sizeof(char));
char s11[10] = "hello";
char* s2=(char*)malloc(10*sizeof(char));
char s22[10] = "world";
char* s3=(char*)malloc(10*sizeof(char));
char s33[10] = "god";
char **ss,**p;
/*
s1="hello";
s2="world";
s3="god";
*/
memcpy(s1,s11,10*sizeof(char));
memcpy(s2,s22,10*sizeof(char));
memcpy(s3,s33,10*sizeof(char));

printf("%p %p %p\n",s1,s2,s3);
printf("%s\n",s1);
printf("%s\n",s2);
printf("%s\n",s3);

ss= (char**)malloc(3*sizeof(char*));
p=ss;
*p= s1;
p++;
*p= s2;
p++;
*p= s3;
p++;
*str=ss;
}

int main(int argc, char *argv[]){
char** str;
// int i;
mc(&str);
printf("%p %p %p\n",*str,*(str+1),*(str+2));
printf("%s\n",*str);
printf("%s\n",*(str+1));
printf("%s\n",*(str+2));

return 0;
}
[解决办法]
你使用指针s1="hello"的时候,知道会发生什么么?将指针s1指向了一块字符串,而你申请的内存将成为僵尸,没有指针能够再去指向它。

C/C++ code
#include <stdio.h>#include <stdlib.h>#include <malloc.h>#include <string.h>void mc(char*** str){    char* s1=(char*)malloc(sizeof(char)*10);    char* s2=(char*)malloc(sizeof(char)*10);    char* s3=(char*)malloc(sizeof(char)*10);    char **ss,**p;    strcpy(s1,"hello");    strcpy(s2,"world");    strcpy(s3,"god");    printf ("%p,%p,%p\n",s1,s2,s3);     ss= (char**)calloc(3,sizeof(char*));    p=ss;    *p= s1;    p++;    *p= s2;    p++;    *p= s3;    p++;    /* printf ("%p\n",p); */    *str=ss;}int main(int argc, char *argv[]){    char** str;    int i;    mc(&str);    printf ("%p\n",*str);    str++;    printf ("%p\n",*str);    str++;    printf ("%p\n",*str);    return 0;} 

热点排行