本文介绍了动态创建2d字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码没有问题,

但地址无法获得。

请提供您的解决方案。

i有以下代码



the below code there is no issue,
but address not able to get.
please provide your solution.
i have below code

#include<iostream.h>
#include<stdlib.h>
void main()
{
    char **array;
    int row,column;
    char temp='A';
    cout<<"enter the Row"<<endl;
    cin>>row;
    cout<<"enter the Column"<<endl;
    cin>>column;
    array=(char **)malloc(row*sizeof(char *));
    for (int i=0;i<row;i++) {
        array[i]=(char*)malloc(column*sizeof(char));
    }

    for(int j=0;j<row;j++)  {
        for (int k=0;k<column;k++)
        {
            cout<<&array[j][k]<<endl;
            array[j][k]=temp;
            cout<<*(*(array+j)+k)<<endl;
            temp++;
        }
    }
}










[edit]Code block added - OriginalGriff[/edit]

推荐答案

#include <vector>

using namespace std;

vector< vector< string > > ArrayOfArrayOfStrings;
vector< string > FirstArrayOfStrings;
FirstArrayOfStrings.push_back( string("A") );

ArrayOfArrayOfString.push_back( FirstArrayOfStrings );





好​​的部分是 malloc 为你完成所有免费,这样你的程序就不会惹事内存,也没有更多硬编码的固定限制或者代码中的魔术数字。

不好的一面是你需要花几个小时来理解和使用迭代器 s正确地输出向量



The good part is all the mallocing gets done for you along with all the freeing so your program doesn''t leek memory and there are no more hard coded fixed limits or ''magic'' numbers in your code.
The down side is you will need to put in some hours to understand and use iterators to do the outputting of the vector properly.


#include <string>
#include <iostream>

int main(int _argc, char* _argv[])
{
    int nX, nY;
    std::cin >> nX;
    std::cin >> nY;

    //create array
    std::string** strArray;
    strArray = new std::string*[nX];
    for(int i = 0; i < nX; i++)
        strArray[i] = new std::string[nY];

    strArray[0][0] = "Hello";
    strArray[nX-1][nY-1] = "World";

    //delete array
    for(int i = 0;  i < nX; i++)
        delete strArray[i];
    delete strArray;
}


这篇关于动态创建2d字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 23:05
查看更多