c - 如何使每次迭代的 printf 都能看到 char 数组单词中的值?当 *a=*b (当一个指针等于另一个指针时)又意味着什么?

标签 c pointers

我的printf声明不起作用。应该有像 abcdefg对于第一次迭代,对于第二次根据 char 数组中的代码等在另一个方向翻转单词 word .

printf("first iteration %s\n",word[1]);
printf("second iteration %s\n", word[2]);
printf("second iteration %s\n", word[3]);
printf("second iteration %s\n", word[4]);

代码:

 #include <stdio.h>


 void flipper(char *a, char *b, char *c) {  char val = *a;  *a = *b; *b
 = *c;  *c = val; }

 int main() {

    char word[] = "abcdefg";

    int i;  for (i = 0; i < 5; i++) {       flipper(&word[i], &word[i+1],
 &word[i+2]);   }

    return 0; }

最佳答案

*a = *b 简单的意思就是将b 指向的对象的值分配给a的对象 指向。在本例中,a 指向 word[i]b 指向 word[i+1],因此 *a = *b 表示您将 word[i+1] 的值分配给 word[i]

让我们来看看对 flipper 的第一次调用。在函数的开头,以下内容成立:

Variable      Points To        Value
--------      ---------        -----
     val        n/a              'a'  // val is initialized at declaration
       a        word[0]          'a'
       b        word[1]          'b'
       c        word[2]          'c'

表达式 *a 相当于表达式 word[0],其计算结果为字符值 'a'

完成所有分配后,我们的变量现在如下所示:

Variable      Points To        Value
--------      ---------        -----
     val        n/a              'a'  // val is initialized at declaration
       a        word[0]          'b'
       b        word[1]          'c'
       c        word[2]          'a'

我们没有更改指针的值 - 它们仍然指向在函数开始时所指向的相同对象。我们更改的是指向对象的内容(word[0]word[1]字[2])。第一次调用 flipper 后,word 看起来像这样:"bcadefg"

要跟踪代码的进度,只需执行以下操作:

for (i = 0; i < 5; i++) 
{
   printf( "%d: before flip - \"%s\"", i, word ); 
   flipper(&word[i], &word[i+1], &word[i+2]); 
   printf( "%d:  after flip - \"%s\"", i, word );
}

关于c - 如何使每次迭代的 printf 都能看到 char 数组单词中的值?当 *a=*b (当一个指针等于另一个指针时)又意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36040242/

相关文章:

c - 如何使用 fgets/read/fread 识别 double\n\n

c - 微 Controller 编程

c++ - 智能指针和指向数组的指针

c - C 语言栈的 Pop() 函数

接收指向结构的二维数组的指针的 C 函数

c - 从两个 128 位 block 中收集四个 32 位字

c - 在 gdb 中,我的变量显示为 <optimised out>,我怎样才能找到它的值?

c - C 运行时静态链接与动态链接中的内存分配

c - C 中的系统命令,如何在 ""之间的字符串内传递指针

c# - 表单是否像指针一样工作?