我在处理以下代码中的数组和指针时遇到了问题:
#include <stdio.h>
#define MAX 1000
void swap (char *v[], int i, int j);
main() {
int i = 1, j = 2;
int count;
char *a = "Bill ", *b = "went ", *c = "to the ", *d = "grocery store.";
char *v[MAX];
v[0] = a;
v[1] = b;
v[2] = c;
v[3] = d;
printf("String before swapping elements at index %d and %d: \n",i,j);
for(count = 0; count < 4; ++count)
printf("%s",v[count]);
printf("\n");
swap(v,i,j);
printf("String after swapping elements at index %d and %d: \n",i,j);
for(count = 0; count < 4; ++count)
printf("%s",v[count]);
printf("\n");
system("Pause");
return 0;
}
void swap (char *v[], int i, int j)
{
char *temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
想到两件事:
v[] = {a,b,c,d}
为什么我声明后不能写*v[MAX]
?事实上,我做了一个快速测试,即使这样也是不允许的:
char v[MAX];
v[] = {'w','o','r','d','s'};
而char v[] = {'w','o','r','d','s'};
被接受。这是为什么?
第二件事,我怎样才能重写 for 循环而不必使用幻数(在本例中为 4)?我尝试以各种方式使用 strlen,但每次都出现错误。我能想到的最好的方法是声明char *k;
和更改循环条件的有点笨拙的解决方案
for(count = 0, k = v; *(k-1); ++count, ++k)
printf("%s",v[count]);
当然必须有一种更优雅的方式来循环遍历 v 数组?