And*_*mel 5 c arrays pointers function char
我正在尝试将初始化的char指针数组传递给函数.我似乎无法弄清楚为什么函数只会打印出数组中每个元素的数字.
有谁知道如何从传入的指针数组中打印每个字符串元素?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
void sort(char *);
int main()
{
char *states[4] = {"Florida", "Oregon", "California", "Georgia"};
sort(*states);
return 0;
}
void sort(char *states)
{
int x;
for (x = 0; x < 4; x++) {
printf("\nState: %d\n", states[x]); //only this will compile
//printf("\nState: %s\n", states[x]); //need to print this.
}
}
Run Code Online (Sandbox Code Playgroud)
你sort如果要打印数组的内容函数必须接受指针数组.
void sort (char *states[], size_t num_states) {
int x;
for (x = 0; x < num_states; ++x) {
printf("\nState: %s\n", states[x]); /* Note %s instead of %d */
}
}
Run Code Online (Sandbox Code Playgroud)
而且,您必须将数组传递给函数.
sort(states, 4);
Run Code Online (Sandbox Code Playgroud)