char *指针分配给char数组,并在其中输出

时间:2014-03-26 04:37:41

标签: c++ arrays pointers

我已经将结构chararray定义如下。

struct chararray
{
    char* lhs;
    char* rhs;
};

现在,我有两个数组la [l]和ra [l](两者都定义了所有l值)。我将它分配给结构,并返回函数。

chararray s;
s.lhs = new char[l];
s.rhs = new char[l];
s.lhs = &la[0]; 
s.rhs = &ra[0];
return s;

主要是我ouptut

for(int i = 1; i < l;i++){
    cout << *(s.rhs + i);
}

现在,我得到了胡言乱语的输出。 但如果我输出*(s.rhs + 0 )和*(s.rhs + 1 )和... [显式包含值0,1,..],我得到正确的输出!

为什么 for 循环不起作用?

PS - 我的整个代码是 -

 #include <iostream>
#include <cstring>
#include <vector>
#include <cmath>

using namespace std;

struct chararray
{
    char* lhs;
    char* rhs;
};

chararray getcenter(char in[],int l){
    int open_count = 0;
    int open = 0;
    int first = 0;
    int last = 0;
    int limit;
    int close_count = 0;
    char lhs[l],rhs[l];
    for(int i = 0; i < l;i++){
        lhs[i] = ' ';
        rhs[i] = ' ';
    }
    for(int i = 0; in[i]!='\0';i++){
        int flag = 0;
        if(in[i] == '('){
            if(flag == 0){first = i;flag = 1;}
            open++;
        }
        if(in[i] == '('){
            last = i;
        }
        limit = i;
    }
    for(int i = 0; in[i]!='\0';i++)
    {
        //cout << "entrt" << endl;
        int temp;
        if(in[i] == '(') { open_count++; }
        if(in[i] == ')') { close_count++; }
        if((open_count == close_count) && (open_count != 0) && (open_count != open))
        {
            //cout << open_count << endl;
            for(int j = 0;j < i+1;j++)
            {
                lhs[j] = in[j];
            }

            lhs[i+1] = ' ';
            lhs[i+2] = ' ';
            for(int j = i+3; in[j]!='\0';j++)
            {
                lhs[j] = ' ';
                rhs[j-i-3] = in[j];//Assuming no space between -> and rhs
                temp = j;
            }
            for(int j = temp;rhs[j] != '\0';j++){
                rhs[j] = ' ';
            }
            for(int j = temp;lhs[j] != '\0';j++){
                lhs[j] = ' ';
            }
            break;
        }
    }
    chararray s;
    s.lhs = new char[l];
    s.rhs = new char[l];
    s.lhs = &lhs[0];    
    s.rhs = &rhs[0];
    return s;
}

int main()
{

    string input;
    cin >> input;
    int l=input.length()+1;
    char in[l];
    strcpy(in, input.c_str());
    chararray s = getcenter(in,l);
    for(int i = 1; i < l;i++){
        //cout << *(s.rhs + i); - Doesnt work
    }
    cout << *(s.lhs + 5); // Works!

    return 0;
}

1 个答案:

答案 0 :(得分:0)

你的for循环从i = 1开始,当你明确设置你使用的值为0和1.确定你想要开始的地方,然后再试一次。

试试这个:

for(int = 0 ; i < l; i++)
    cout << *(s.rhs + i);

请注意,使用以下代码行实际上存在内存泄漏风险:

s.lhs = new char[l];
s.rhs = new char[l];
s.lhs = &lhs[0];    
s.rhs = &rhs[0];

您正在分配1个字符并将其地址存储在s.lhs中,然后将s.lhs重置为lhs [0]的地址。其中第一行不需要new。所以用这个替换代码:(另请注意&amp; lhs [0]与lhs相同)

s.lhs = lhs;
s.rhs = rhs;