gpt4 book ai didi

c - 如何在 C 中通过引用将数组指针传递给函数?

转载 作者:行者123 更新时间:2023-11-30 17:26:59 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>

void populateArray(char* line, char** cmd){
printf("INPUT LINE: %s\n", line);
char * token = strtok (line, " ");
int n_spaces = 0, i;

/* split string and append tokens to 'cmd' */

while (token) {
*cmd = realloc (*cmd, sizeof (char*) * ++n_spaces);

if (*cmd == NULL)
exit (-1); /* memory allocation failed */

*cmd[n_spaces-1] = token;

token = strtok (NULL, " ");
}

/* realloc one extra element for the last NULL */

*cmd = realloc (*cmd, sizeof (char*) * (n_spaces+1));
*cmd[n_spaces] = 0;

/* print the cmd */

for (i = 0; i < (n_spaces+1); ++i)
printf ("cmd[%d] = %s\n", i, cmd[i]);
}

int main (int argc, char* argv[])
{
char *cmd1 = NULL;
char * line = "ls -l";
populateArray(line, &cmd1);
}

我知道 C 是按值传递,但是有没有办法模拟它按引用传递?我需要将 cmd1 传递给 populateArray(char* line, char** cmd) 作为引用。我做了一些研究并在 C 中通过引用传递,似乎我需要做这样的事情:我尝试过,但仍然无法使其适用于数组指针。

void byreference_func(int* n){
*n = 20;
}
int main(int argc, char *argv[])
{
int i = 10;
printf("before the call the value of i is %d\n", i);
byreference_func(&i);
printf("after the call the value of i is %d\n", i);
return 0;
}

编辑:错误代码

anon@turing:~/csce3613/assign3$ gcc gg.c
gg.c: In function âpopulateArrayâ:
gg.c:6:24: warning: initialization makes pointer from integer without a cast [enabled by default]
gg.c:17:23: warning: assignment makes integer from pointer without a cast [enabled by default]
gg.c:19:13: warning: assignment makes pointer from integer without a cast [enabled by default]
anon@turing:~/csce3613/assign3$ ./a.out
INPUT LINE: ls -l
Segmentation fault (core dumped)

最佳答案

cmd1 是一个数组。数组无法重新分配。您只能在空指针或之前调用 malloc 系列函数返回的指针上使用 realloc

相反,您需要执行以下操作:

int main() 
{
char *cmd1 = NULL;
populateArray( line, &cmd1 );
}

然后在函数内,将 cmd 更改为 (*cmd)。它与您的 int 示例完全相同,只不过该示例中所有 int 都需要将其更改为 char *。您在 int 示例中正确编写了 *n = 20; 但随后您忘记在实际代码中执行此操作。

顺便说一句,如果您总是在返回之前free,那么您并没有真正填充数组,并且。

关于c - 如何在 C 中通过引用将数组指针传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26569378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com