我用 C 编写了一个简单的程序来检查两个单词是否是字谜。我的问题是,如果我传递 word_one 和 word_two 作为参数,这是否意味着我没有修改原始数组?我认为我正在有效地处理这些未归还的副本。
这意味着我不应该能够将它们与我的 equal_array 函数进行比较。
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#define MAXLENGTH ((int) (sizeof(letters) / sizeof(letters[0])))
void read_word(int counts[26]);
bool equal_array(int counts[26], int counts2[26]);
int main(void){
int word_one[26] = { 0 };
int word_two[26] = { 0 };
printf("Enter first word: ");
read_word(word_one);
printf("Enter second word: ");
read_word(word_two);
if (equal_array(word_one, word_two))
printf("These words are anagrams!");
else
printf("These words not are anagrams!");
return 0;
}
void read_word(int counts[26]){
char ch;
while ((ch = getchar()) != '\n'){
ch = toupper(ch);
if (ch >= 'A' && ch <= 'Z'){
counts[(ch - 'A')]++;
}
}
}
bool equal_array(int counts1[26], int counts2[26]){
int i;
bool equal = true;
for (i = 0; i < 26; i++) {
if (counts1[i] != counts2[i]) {
equal = false;
break;
}
}
return equal;
}
C 确实总是按值传递,但是当数组传递给函数时,它们always即使您在参数声明中指定了长度,也会衰减为指针。发生的情况是你的声明
void read_word(int counts[26])
相当于
void read_word(int * counts)
当你通过时word_one
and word_two
对于您的函数,它们收到的值是数组第一个元素的地址。这些仍然指向原始数组,因此,当您在函数中修改它们时,结果也在原始数组中可见。
ADDIT
有趣但鲜为人知的旁注:在 C99 及更高版本中,您可以声明您的函数,其长度前面为static
, 如下:
void read_word(int counts[static 26])
这并没有改变函数接收地址副本而不是整个数组的事实,但它确实允许编译器优化和检测潜在错误。在这种情况下read_word
上面,如果你传递一个,编译器会发出警告NULL
- 指向函数的指针,或少于 26 个元素的数组。更多内容可阅读here.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)