char *name[]={"Follow me","BASIC","Great Wall","FORTRAN","Computer design"}; 在函数f1中比较字符串长度,在主函数中输出最长的字符串
时间: 2023-12-11 18:33:24 浏览: 25
以下是实现上述功能的C语言代码:
```c
#include <stdio.h>
#include <string.h>
void f1(char *name[], int len, char **max) {
int max_len = 0;
for (int i = 0; i < len; i++) {
int cur_len = strlen(name[i]);
if (cur_len > max_len) {
max_len = cur_len;
*max = name[i];
}
}
}
int main() {
char *name[] = {" me", "BASIC", "Great Wall", "FORTRAN", "Computer design"};
int len = sizeof(name) / sizeof(name[0]);
char *max = NULL;
f1(name, len, &max);
printf("The longest string is: %s\n", max);
return 0;
}
```
相关问题
char* name[] = { "BASIC","FORTRAN","C++","Pascal","COBOL" };为什么会报错
这段代码定义了一个字符串数组,其中每个元素都是一个字符串常量。但是,这里使用的是字符指针数组,而不是字符串数组。因此,需要将每个字符串常量转换为字符指针,即在每个字符串常量前加上一个“&”符号。修改后的代码如下:
```
char* name[] = { &"BASIC",&"FORTRAN",&"C++",&"Pascal",&"COBOL" };
```
这样就可以正确地定义一个字符指针数组了。
定义指针数组,使其指向字符串常量:char * name[4]={“Follow”,,“Great”, “FORTRAN”,“Computer”},并进行排序。实际是对指针指向的排序,字符串不动!
好的,我来给你解答这个问题。
首先,我们需要明确指针数组的定义方式,即 char * name[4],这里定义了一个长度为 4 的指针数组,每个元素都是一个指向 char 类型的指针。
其次,我们需要对指针数组进行初始化,使其指向字符串常量。可以这样写:
```
char * name[4] = {"Follow", "Great", "FORTRAN", "Computer"};
```
注意,这里的字符串常量需要使用双引号括起来,而且每个字符串常量之间需要用逗号隔开。
最后,我们需要对指针数组中的指针进行排序。由于我们只是对指针进行排序,所以字符串常量的顺序不会发生改变。可以使用 C 语言标准库中的 qsort 函数来进行排序,具体代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void * a, const void * b) {
char *pa = *(char **)a;
char *pb = *(char **)b;
return strcmp(pa, pb);
}
int main() {
char * name[4] = {"Follow", "Great", "FORTRAN", "Computer"};
int i;
qsort(name, 4, sizeof(char *), compare);
for (i = 0; i < 4; i++) {
printf("%s\n", name[i]);
}
return 0;
}
```
这里的 compare 函数用来比较两个指针指向的字符串的大小关系,然后 qsort 函数会根据比较结果对指针数组进行排序。
希望我的解答能够帮到你,如果你还有其他问题,可以继续提问哦!
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)