C++ 在方法c中传递双指针
为什么当双指针作为单指针发送到函数并被访问时,在尝试分配内存时不会出现错误,即使在堆上分配内存,也会导致分段错误C++ 在方法c中传递双指针,c++,c,pointers,C++,C,Pointers,为什么当双指针作为单指针发送到函数并被访问时,在尝试分配内存时不会出现错误,即使在堆上分配内存,也会导致分段错误 将双指针作为双指针参数传递给函数-效果良好 #include <stdio.h> #include <stdlib.h> #include <string.h> void to_fun(char **dbl_ptr) { *dbl_ptr = malloc(20); strcpy(
将双指针作为双指针参数传递给函数-效果良好
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void to_fun(char **dbl_ptr)
{
*dbl_ptr = malloc(20);
strcpy(*dbl_ptr,"cool");
}
void main( )
{
char **dbl_ptr = calloc ( 2 , sizeof(char *) );
to_fun ( (dbl_ptr + 1) );
printf("%s\n",*(dbl_ptr + 1) );
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void to_fun(char *dbl_ptr)
{
printf("%s\n",dbl_ptr );
}
void main( )
{
char **dbl_ptr = calloc ( 2 , sizeof(char *) );
*(dbl_ptr + 1) = "cool";
to_fun ( *(dbl_ptr + 1) );
}
#包括
#包括
#包括
无效到乐趣(字符**dbl\u ptr)
{
*dbl_ptr=malloc(20);
strcpy(*dbl_ptr,“酷”);
}
空干管()
{
char**dbl_ptr=calloc(2,sizeof(char*));
to_fun((dbl_ptr+1));
printf(“%s\n”,*(dbl_ptr+1));
}
将双指针作为单指针参数传递给函数
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void to_fun(char *dbl_ptr)
{
dbl_ptr = malloc(20);
strcpy(dbl_ptr,"defnitely not cool");
}
void main( )
{
char **dbl_ptr = calloc ( 2 , sizeof(char *) );
to_fun ( *(dbl_ptr + 1) );
printf("%s\n",*(dbl_ptr + 1) );
}
#包括
#包括
#包括
void to_fun(char*dbl_ptr)
{
dbl_ptr=malloc(20);
strcpy(dbl_ptr,“不酷”);
}
空干管()
{
char**dbl_ptr=calloc(2,sizeof(char*));
to_fun(*(dbl_ptr+1));
printf(“%s\n”,*(dbl_ptr+1));
}
将双指针作为单指针参数传递给函数-效果良好
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void to_fun(char **dbl_ptr)
{
*dbl_ptr = malloc(20);
strcpy(*dbl_ptr,"cool");
}
void main( )
{
char **dbl_ptr = calloc ( 2 , sizeof(char *) );
to_fun ( (dbl_ptr + 1) );
printf("%s\n",*(dbl_ptr + 1) );
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void to_fun(char *dbl_ptr)
{
printf("%s\n",dbl_ptr );
}
void main( )
{
char **dbl_ptr = calloc ( 2 , sizeof(char *) );
*(dbl_ptr + 1) = "cool";
to_fun ( *(dbl_ptr + 1) );
}
#包括
#包括
#包括
void to_fun(char*dbl_ptr)
{
printf(“%s\n”,dbl\u ptr);
}
空干管()
{
char**dbl_ptr=calloc(2,sizeof(char*));
*(dbl_ptr+1)=“酷”;
to_fun(*(dbl_ptr+1));
}
这只是一个示例代码,让您了解问题..它并不意味着像即兴创作的一个废话废话
我知道指针和解引用是如何深入工作的,但上面这些东西仍然很烦人。任何人都可以解释原因 第一个代码块之所以有效,是因为您传递了一个指针,然后取消引用该指针以修改指针指向的内容(即在
main
中分配的内存块)
对于第二个代码块,您正在修改函数参数dbl\u ptr
。对函数参数的更改不会反映在调用函数中,因为所有参数都是按值传递的
第三段代码之所以有效,是因为您正在读取函数参数并取消对指向有效内存的指针值的引用
另外,您没有将char**
传递给第二个和第三个函数,而是将char*
传递给第二个和第三个函数
您在main
中也没有分配足够的内存。您分配了2个字节,但需要的是2char*
的空间:
char **dbl_ptr = calloc ( 2 , sizeof(char *) );
如果要从函数内部修改变量,且该变量不在函数的作用域内,请传递一个指向该变量的指针:
void f(double *x) {
*x = 12;
}
void main() {
double z;
f(&z);
printf("%f", z);
}
如果变量是指针,则需要指向指针的指针:
void f(double **x) {
*x = malloc(...);
}
void main() {
double *z;
f(&z);
printf("%f", z[1]);
}
什么是
calloc(2,1)代码>应该怎么做?特别是为什么代码> 2 < /代码>和<代码> 1代码>代码?除了不同的字符串之外,第一个代码代码和第二个代码示例之间有什么不同?OOP我的坏,固定的NoC ++是与C不同的语言,并且C++中的这种考虑与C中的不同。选择第二个和第三个示例不通过[A]作为单指针参数指向函数的双指针”。它们将单个指针(一个char*
)传递给函数,而函数又需要一个正是该类型的参数。是。就这么简单。