Yes ,I can ! 2020-11-24 18:27 采纳率: 0%
浏览 3

为什么没有输出呢?我得目的是想通过字符数组buffer[]对buf初始化,怎么实现呢?

#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
using namespace std;

int main()
{
    char buffer[100];
    char *buf[50];
    strcpy(buffer, "helloooo");
    strcpy(buf[0], buffer);

    strcpy(buffer, "hellooo");
    strcpy(buf[1], buffer);

    strcpy(buffer, "helloo");
    strcpy(buf[2], buffer);

    strcpy(buffer, "hell");
    strcpy(buf[3], buffer);

    cout<<buf[0]<<endl;
    cout<<buf[1]<<endl;
}

  • 写回答

1条回答 默认 最新

  • mango205 2020-11-24 19:58
    关注

    出问题的原因是你忘记给"指向字符串的指针"分配内存空间

    int main()
    {
        char buffer[100];
        char* buf[50];

        for (int i = 0; i <= 3; i++) {
            buf[i] = (char*)malloc(sizeof(char*));
        }
        
        strcpy(buffer, "helloooo");
        strcpy(buf[0], buffer);

        strcpy(buffer, "hellooo");
        strcpy(buf[1], buffer);

        strcpy(buffer, "helloo");
        strcpy(buf[2], buffer);

        strcpy(buffer, "hell");
        strcpy(buf[3], buffer);

        cout << buf[0] << endl;
        cout << buf[1] << endl;
    }

    评论

报告相同问题?