注册 登录
编程论坛 C语言论坛

求大佬帮忙看一下 总是在a[]这个位置说a[i]里的i要是指针形式

q1822622 发布于 2020-01-03 15:41, 1283 次点击
#include<stdio.h>
#include<string.h>
struct fruit
{
    int id;
    char name[20];
    int height;
    float weight;
}a[]={{001,"Apple",67,58},{002,"Banana”",75,70.5},{003,"Peach",65,57.5},{004,"Pineapple",60,55},{005,"Grape",80,76.5},{006,"Kiwi",78,68.9}};fruit temp;
main()
{
    int i,j,a;
    struct fruit *j    ;
    for(i=0;i<6;i++)
    {
        for(j=0;j<6-i-1;j++)
        {
            if(strlen(a[j].name<strlen(a[j+1].name)))
            {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
            }
            else if(strlen(a[j].name)<strlen(a[j+1].name)&&a[j].weight<a[j+1].weight)
            {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
            }
        }
    }
    for(a=1;a<=6;a++)
    {
        printf("a[a]");
    }
}
1 回复
#2
rjsp2020-01-03 17:03
#include <stdio.h>
#include <string.h>

struct fruit
{
    int id;
    char name[20];
    int height;
    float weight;
};

int main( void )
{
    struct fruit a[] = { {001,"Apple",67,58.f},{002,"Banana",75,70.5f},{003,"Peach",65,57.5f},{004,"Pineapple",60,55.f},{005,"Grape",80,76.5f},{006,"Kiwi",78,68.9f} };

    const size_t n = sizeof(a)/sizeof(*a);
    for( size_t i=0;i!=n; ++i )
    {
        for( size_t j=0; j!=n-i-1; ++j )
        {
            if( strlen(a[j].name)<strlen(a[j+1].name) || (strlen(a[j].name)==strlen(a[j+1].name) && a[j].weight<a[j+1].weight) ) // 你的源代码看不懂。竟然根据“名字长度”来排序?!!!
            {
                struct fruit temp = a[j];
                a[j] = a[j+1];
                a[j+1] = temp;
            }
        }
    }
    for( size_t i=0;i!=n; ++i )
    {
        printf( "%d, %s, %d, %f\n", a[i].id, a[i].name, a[i].height, a[i].weight );
    }
}
1