Tag: 传递引用

对传递引用感到困惑

考虑以下示例,我尝试以C方式传递引用: // Function prototypes void increment(unsigned* number); int main() { unsigned* thing; increment(thing); cout << *thing; return 0; } void increment(unsigned* number) { number = (unsigned*) malloc(sizeof(unsigned)); *number = 1; } 我在行cout << *thing遇到程序崩溃。 是的,我在这里使用C ++但是我想尝试C版本的pass-by-reference,因为我的主要项目是在C. 我通过更改代码修复它,如下所示: // Function prototypes void increment(unsigned** number); int main() { unsigned* thing; increment(&thing); cout << *thing; return 0; } […]

修改C中的const char *

我正在练习面试。 我目前坚持的问题是在C中反转一个常量字符串。我知道,因为str2是const,我可以修改str2指向的位置,但不能修改它的值。 我有一个名为reverse_const的函数。 它会将const char * str_const反转并打印出来。 但是,当我尝试从main方法反转后打印st2时,字符串不再反转。 它就像reverse_const()暂时改变了str2的内存位置。 我在这做错了什么? #include #include void reverse(char *str){ int c_size = strlen(str); char *c_begin = str, *c_end = str + (c_size – 1); int i; for(i = 0; i < c_size / 2; i++){ *c_begin ^= *c_end; *c_end ^= *c_begin; *c_begin ^= *c_end; c_begin++; c_end–; } } void […]

通过引用将字符串数组传递给C函数

我很难通过引用将一个字符串数组传递给函数。 char* parameters[513]; 这代表513个字符串吗? 以下是我初始化第一个元素的方法: parameters[0] = “something”; 现在,我需要通过引用将’参数’传递给函数,以便函数可以向其添加更多字符串。 函数头如何看起来如何在函数内部使用此变量?

如何通过引用传递动态分配的2D数组中的子数组?

我需要传递引用子数组,它是动态分配的2D数组的一部分。 我尝试了以下方法,似乎不起作用。 任何想法,如果有可能吗? void set1(int *a){ a = malloc(2*sizeof(int)); a[0] = 5; a[1] = 6; } void set2(int *a){ a = malloc(2*sizeof(int)); a[0] = 7; a[1] = 8; } int main(){ int **x = malloc(2*sizeof(int*)); set1(x[0]); set2(x[1]); return 0; }

在C中通过引用传递字符串

我无法弄清楚如何通过函数的参数传回字符串。 我是编程新手,所以我想这可能是一个初学者的问题。 你能给予的任何帮助都将非常感激。 这段代码出错了,我不知道为什么,但是我提供的代码是为了展示我到目前为止的内容。 我已将其设为社区维基,因此您可以自由编辑。 PS这不是功课。 这是原始版本 #include #include #include void fn(char *baz, char *foo, char *bar) { char *pch; /* this is the part I’m having trouble with */ pch = strtok (baz, “:”); foo = malloc(strlen(pch)); strcpy(foo, pch); pch = strtok (NULL, “:”); bar = malloc(strlen(pch)); strcpy(bar, pch); return; } int main(void) { […]

在C和C ++中通过引用传递的含义?

我对C和C ++中“通过引用传递”的含义感到困惑。 在C中,没有参考。 所以我猜通过引用传递意味着传递一个指针。 但是为什么不通过指针调用它呢? 在C ++中,我们有指针和引用(和迭代器之类的东西很接近)。 那么通过引用传递的是什么意思呢?