我正在尝试了解指针和指针数组的工作方式。我在此程序中不了解什么?

问题描述 投票:0回答:1
int main(){
  int i, department_quantity;
  char *passer[8];
  char *department_id = malloc(8);

  printf("Enter number of departments:");
  scanf("%d", &department_quantity);

  for(i = 0; i < department_quantity; i++){
      printf("Enter ID of department #%d\n", i + 1);
      scanf("%s", department_id);
      passer[i] = departmemt_id;
  }

  string_array(&passer[0], department_quantity);

}

void string_array(char *array[], size_t length) {
    int i ;
    for (i = 0; i < length; i++) {
        printf("\n%s\n", array[i]);
    }
}

示例输出:

   Enter number of departments:2

   Enter id of department #1

   hello

   Enter id of department #2

   world

   world

   world

我试图理解为什么我无法使程序输出不同的用户输入,即hello world,而不是“ world world”。我对这里的指针不了解?

c arrays function function-pointers
1个回答
0
投票

departmemt_id只是同一块内存。对于每个输入(每次迭代),您都在相同的内存地址进行写入,从而有效地覆盖了先前的内容。因此,最后您所拥有的就是您输入的最后一个单词。请注意,passer将包含等效元素(指针相同)。

© www.soinside.com 2019 - 2024. All rights reserved.