【发布时间】:2013-06-18 01:20:26
【问题描述】:
这个问题来自 Zed Shaw 的 Learn C the Hard Way。这是关于指针和数组的。我们在这里给出了一些代码:
#include <stdio.h>
int main(int argc, char *argv[])
{
// create two arrays we care about
int ages[] = {23, 43, 12, 89, 2};
char *names[] = {
"Alan", "Frank",
"Mary", "John", "Lisa"
};
// safely get the size of ages
int count = sizeof(ages) / sizeof(int);
int i = 0;
// first way using indexing
for(i = 0; i < count; i++) {
printf("%s has %d years alive.\n",
names[i], ages[i]);
}
printf("---\n");
// setup the pointers to the start of the arrays
int *cur_age = ages;
char **cur_name = names;
// second way using pointers
for(i = 0; i < count; i++) {
printf("%s is %d years old.\n",
*(cur_name+i), *(cur_age+i));
}
printf("---\n");
// third way, pointers are just arrays
for(i = 0; i < count; i++) {
printf("%s is %d years old again.\n",
cur_name[i], cur_age[i]);
}
printf("---\n");
// fourth way with pointers in a stupid complex way
for(cur_name = names, cur_age = ages;
(cur_age - ages) < count;
cur_name++, cur_age++)
{
printf("%s lived %d years so far.\n",
*cur_name, *cur_age);
}
return 0;
}
指令是给“rewrite all the array usage in this program so that it's pointers.”的意思是不是做类似的事情?
int *ptr;
ptr = &ages[0]
【问题讨论】:
-
这也可能意味着使用
malloc动态分配数组。关于您的ptr分配ptr = ages;应该足够了。 -
指针和数组在很多情况下是可以互换的。例如,在顶部,*argv[] 可以替换为 **argv。您可以通过简单地删除所有方括号并在每个数组的前面放置一个 * 来完成分配。
-
你能提供一个链接到有问题的确切练习吗?
-
BTW - 如果代码有注释“安全地获取年龄大小”,这是错误的;如果有人更改了年龄的类型,则会给出错误的值。获取年龄大小的更安全方法是
sizeof(ages) / sizeof(*ages)。