在 C 中使用双重引用更改 char 数组

标签 c pointers

为什么会这样

char** p;
char* s = (char*)malloc(6);
strcpy(s,"abcde");
s[2] = 'f';
printf("%s",s);
*p = s;
p[0][2] = 'g';
printf("\n%s",*p);

输出:

abfde
abgde

但这不是

char** p;
char* s = (char*)malloc(6);
strcpy(s,"abcde");
s[2] = 'f';
printf("%s",s);
*p = s;
*p[2] = 'g';
printf("\n%s",*p);

输出:

abfde
abfde

为什么在第一种情况下使用索引访问位置 (p[0][2]) 有效但使用引用 (*p[2]) 无效?

最佳答案

第一个代码有未定义的行为,当 *p = s; 发生时,p 未初始化。因此,它不“工作”;任何事情都可能发生。

也就是说,查看运算符优先级规则。

关于在 C 中使用双重引用更改 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46097840/

相关文章:

c - C 中的 for 循环导致无限循环的示例

c - 如何安全使用strnlen?

c++ - 从指针 vector 中删除对象

C 通过指针将数组传递给函数

c - 打开文件时出现 SIGSEGV 错误

c - 使用 GtkTextBuffer 意外中止

c - C中泊松分布的计算

c - 在另一个字符串中的每个字符之前附加相同的字符串

c - C 编程中的访问指针

c - C指针的 "**&ptr"和 "2**ptr"是什么意思?