内容纲要

输入月份号,输出对应月份

#include<iostream>
using namespace std;
void Count(int *a);
int *Cins();
int a;
int s = 13;
void main()
{

    Count(Cins());
    system("pause");
}
void Count(int *a)
{
    char s1[] = { "一月;" };
    char s2[] = { "二月;" };
    char s3[] = { "三月;" };
    char s4[] = { "四月;" };
    char s5[] = { "五月;" };
    char s6[] = { "六月;" };
    char s7[] = { "七月;" };
    char s8[] = { "八月;" };
    char s9[] = { "九月;" };
    char s10[] = { "十月;" };
    char s11[] = { "十一月;" };
    char s12[] = { "十二月;" };
    char s13[] = {"超出范围;"};
    char *s[13] = {s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13 };
    *a = *a - 1;
    cout<<*(s +*a);
}
int *Cins()
{
    cout<< "输入一个数字;" << endl;
    cin >> a;
    if (a > 0 && a < 12)
    {
        return &a;
    }
    else
    {
        return &s;
    }
}

对n个字符串排序,(一维指针数组)

#include <iostream>
using namespace std;
void Count(char **p, int nl);
void Cout(char **p, int ss);
void main()
{
    char a1[] = "zzzz4;";
    char a2[] = "ffff;";
    char a3[] = "cccc66;";
    char a4[] = "哇哈哈哈哈;";
    char a5[] = "eeee;";
    char *p[6] = { a1,a2,a3,a4,a5};//这里有个问题,指针字符串长度一定要,多出一个长度,否则会说堆栈损坏???
    Count(p, 5);
    system("pause");
}
void Count(char **p, int nl)
{
    nl = nl - 1;
    for (int a = 0; a < nl+1 ; a++)
    {
        for (int i = 0; i < nl - a; i++)
        {
            int x = strcmp(*p + i, *p + i + 1);//核心思想,改变地址位置;直接改变值的方法不太行,应为字符串的长短不一,用来储存的字符串无法确定长度;
            char *p6=NULL;
            if (x > 0)
            {
                p6 = p[i];
                p[i] = p[i + 1];
                p[i + 1] = p6;
            }
        }
    }
    Cout(p, nl+1);
}
void Cout(char **p, int ss)
{
    for (int x = 0; x < ss; x++)
    {
        cout << *(p + x);
    }
}

对n个字符串排序,用二维数组

#include<iostream>
using namespace std ;
void sort(char name[][20], int nl);
void main()
{
    char p[4][20] = { "hahahahaha;","hehehe;","lala;","要你挂;" };
    sort(p,4);
    system("pause");
}
void sort(char name[][20],int nl)
{
    for (int i=0;i<nl-1;i++)
    {
        for (int x=0;x<nl-i;x++)
        {
            int z = strcmp(*(name + i), *(name + i + 1));
            if (z<=0)
            {
                char names[20];
                strcpy_s(names,name[i]);
                strcpy_s(name[i], name[i+1]);
                strcpy_s(name[i + 1], names);

            }
        }
    }
    for (int i=0;i<nl;i++)
    {
        cout << name[i];
    }
}

注意:用strcpy会出问题,要改成strcpy—s

比较第二题第三题做法的优缺点,从时间和空间的代价去比较

运用指针比运用数组要好的多,在运用数组时,会反复开辟和销毁内存,增加程序运行时间。

1 对 “c++基础 指针练习题(2)”的想法;

  1. Pingback: viagra online

发表评论