计算最长字符串的长度

img


有没有可以看看哪里不对吗,显示没error,但是运行不了,不知道是哪里出现的问题,希望大家可以帮我解决一下,谢谢

ch定义为二维字符数组,因为如果是字符指针数组,存储不了多个字符串。

然后将函数第一个参数修改下类型即可。

修改如下:

参考链接:


#include <stdio.h>
#include <string.h>

// https://blog.csdn.net/Lc_summer/article/details/109620744
// 函数第一个参数修改为 指向包含100个字符的数组的指针 
int max_len(char s[][100],int n);

int main(void){
    
    int n,i,j;
    // 因为要存储多个字符串,所以将ch定义为二维字符数组 
    char ch[10][100];
    scanf("%d",&n);
    
    for(i=0;i<n;i++){
        scanf("%s",ch[i]);
    }
    
    j=max_len(ch,n);
    printf("%d",j);
    
    return 0;
}

int max_len(char s[][100],int n){
    
    int a=strlen(s[0]),i,b;
    
    for(i=1;i<n;i++){
        b=strlen(s[i]);
        if(a<b){
            a=strlen(s[i]);
        }
    }
    
    return a;
}

img

代码先格式化一下。看着太费劲了

这题的题目是怎样的?

指针数组要分配空间!
仅供参考,谢谢!

img

#include<stdlib.h>
#include <stdio.h>
#include <string.h>

int max_len(char *s[], int n);
int main(void)
{
    int n, i, j;

    scanf("%d", &n);
    char *ch[n];
    // 要为指针数组分配动态空间
    for (i = 0; i < n; i++)
    {
        ch[i] = malloc(sizeof(char) * 256);
        scanf("%s", ch[i]);
    }

    j = max_len(ch, n);
    printf("%d", j);
    return 0;
}

int max_len(char *s[], int n)
{
    int a = strlen(s[0]), i, b;
    for (i = 1; i < n; i++)
    {
        b = strlen(s[i]);
        if (a < b)
        {
            a = strlen(s[i]);
        }
    }
    return a;
}


没有为 字符串分配存储空间