gpt4 book ai didi

C 修改全局字符数组

转载 作者:行者123 更新时间:2023-11-30 21:35:06 32 4
gpt4 key购买 nike

我在 C 语言中遇到问题。我想在 function1 中更新/修改全局字符串(字符数组)

如何更新变量 dest 并与 main 函数共享?

编辑:我找到了解决方案

char *alphabet;

int function1(char* newstring) {


alphabet = (char*)malloc(63);

printf ("%s\n", alphabet);


strcpy(alphabet, newstring);

return 0;
}

int main() {
char* test="newstring";
function1(test);

printf ("%s\n", alphabet);

return 0;

最佳答案

让我们看看 gcc 对您的代码有什么看法:

gcc -Wall test.c -o test

test.c: In function ‘function1’:
test.c:8:25: warning: comparison between pointer and integer
while (newstring[i] != NULL) {
^~
test.c:9:7: warning: implicit declaration of function ‘strcpy’ [-Wimplicit-function-declaration]
strcpy(dest, newstring[i]);
^~~~~~
test.c:9:7: warning: incompatible implicit declaration of built-in function ‘strcpy’
test.c:9:7: note: include ‘<string.h>’ or provide a declaration of ‘strcpy’
test.c:9:20: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion]
strcpy(dest, newstring[i]);
^~~~~~~~~
test.c:9:20: note: expected ‘const char *’ but argument is of type ‘char’
test.c: In function ‘main’:
test.c:19:20: warning: comparison between pointer and integer
while (dest[i] != NULL) {
^~
test.c:20:22: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
printf ("[%d] %s\n", i, dest[i]);
^
test.c: At top level:
test.c:3:6: warning: array ‘dest’ assumed to have one element
char dest[];
^~~~

正如您所看到的,有很多警告需要注意。

Take warnings seriously and fix them.

这样做的代码可能是:

#include <stdio.h>

char dest[32];

int function1(char* newstring) {
// Or simply use strcpy instead of a loop...
int i = 0;
while(newstring[i] != '\0')
{
dest[i] = newstring[i];
++i;
}
dest[i] = '\0';
return 0;
}

int main() {
char* test="newstring";
function1(test);
int i = 0;
while (dest[i] != '\0') {
printf ("[%d] %c\n", i, dest[i]);
++i;
}
return 0;
}

输出:

[0] n
[1] e
[2] w
[3] s
[4] t
[5] r
[6] i
[7] n
[8] g

注意 您还应该检查缓冲区溢出,即 i 始终小于 32。为了清楚起见,我省略了这一点,但请确保在代码之前添加它视为完成..

关于C 修改全局字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48538425/

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