动态创建2d字符串数组 [英] Creating 2d string array dynamically

查看:71
本文介绍了动态创建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]

推荐答案

您好像已经分配了一个<$ c的2D数组$ c> char 而不是2D字符串数组。但是,这可能是也可能不是你想要的。你已经将这个问题标记为C ++,但似乎是在写''C''。更多C ++方式可能包括其他方面: -



You seem to have allocated a 2D array of char instead of a 2D array of strings. However this may or may not be what you intended. You''ve tagged the question as C++ but seem to be writing ''C''. A more C++ way of doing this might include amongst other lines:-

#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字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆