c++ primer 练习 3.37、3.38、3.39、3.40

3.37

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
    const char ca[] = {'h', 'e', 'l', 'l', 'o'};
    const char *cp = ca;
    while (*cp) {
        cout << *cp << endl;
        ++cp;
    }
    return 0;
}
out:

h
e
l
l
o


a

3.38

纯属搬运

Pointer addition is forbidden in C++, you can only subtract two pointers.

The reason for this is that subtracting two pointers gives a logically explainable result - the offset in memory between two pointers. Similarly, you can subtract or add an integral number to/from a pointer, which means "move the pointer up or down". Adding a pointer to a pointer is something which is hard to explain. What would the resulting pointner represent?

If by any chance you explicitly need a pointer to a place in memory whose address is the sum of some other two addresses, you can cast the two pointers to int, add ints, and cast back to a pointer. Remember though, that this solution needs huge care about the pointer arithmetic and is something you really should never do.

3.39

1

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
#include<cstring>
int main()
{
    const char ca1[] = "string-A";
    const char ca2[] = "string-B";
    if (strcmp(ca1 , ca2) > 0) {
        cout << "string-A big" << endl;
    } else {
        cout << "string-B big" << endl;
    }
    return 0;
}

2

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
#include<string>
using std::string;
int main()
{
    string s1 = "string-A";
    string s2 = "string-B";
    cout << "Big one is: ";
    if (s1 > s2) {
        cout << s1 << endl;
    } else {
        cout << s2 << endl;
    }
    return 0;
}


3.40

#include<cstring>
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
    char s1[100] = "stringA";
    char s2[] = "stringB";
    strcat(s1 , s2);
    char s[100];
    strcpy(s , s1);
    cout << s << endl;
    return 0;
}



  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值