数据结构学习day1

练习:要求在堆区申请6个int类型空间存放6名学生的成绩,分别使用函数实现申请空间、输入学生成绩、输出学生成绩、对学生进行升序排序、释放空间。

#include
#include
#include

//排序

void paixu(int *p, int n)
{
    for(int i=0; i     {
        for(int j=0; j         {
            if(*(p+j)>*(p+j+1))
            {
                int temp = *(p+j);
                *(p+j) = *(p+j+1);
                *(p+j+1) = temp;

            }
        }
    }
}

//定义从堆区申请空间的函数,num表示要申请空间的个数

int *memory(int num)
{
    int *ptr = (int *)malloc(sizeof(int) * num);
    
    //判断是否申请成功
    
    if(NULL == ptr)
    {
        printf("内存申请失败\n");
        return NULL;
    }else
    {
        printf("申请成功\n");
        return ptr;
    }
}

//定义释放空间函数

void myFree(int *ptr)
{
    if(NULL != ptr)
    {
        free(ptr);
        ptr = NULL;
    }
}

//输入 

void input(int *ptr, int n)
{
    if(NULL != ptr)
    {
        for(int i=0; i         {
            printf("请输入第%d个学生的成绩:", i+1);
            scanf("%d", ptr+i);
        }
    }
}

//输出

void out(int *p, int n)
{
    int i;
    for(i=0; i     {
        printf("%-4d", *(p+i));
    }
    putchar(10);
}

int main(int argc, const char *argv[])
{
    int *p1 = memory(6);

    input(p1, 6);
    paixu(p1, 6);
    out(p1, 6);

    myFree(p1);
    p1 = NULL; 
    return 0;
}

 

#include
#include
#include

struct Commodity
{
    char name[20];
    char position[30];
    double price;
    double weight;
};

void PrintCommodity(struct Commodity com)
{
    printf("商品名是%s\n", com.name);
    printf("产地是%s\n", com.position);
    printf("价格是%lf\n", com.price);
    printf("重量是%lf克\n", com.weight);
}
int main(int argc, const char *argv[])
{
    struct Commodity com1;
#if 1
    strcpy(com1.name, "yaogao");
    strcpy(com1.position, "shanghai");
    com1.price = 12.45;
    com1.weight = 100;
#endif

    PrintCommodity(com1);
    return 0;
}

 

思维导图

 

你可能感兴趣的:(数据结构,学习,算法)