简体   繁体   中英

Why can't I assign anything to an array anymore

I have this implementation of a linked list class (using char arrays for strange reason)

list_node::list_node(const std::string & input, int start, int end) {
std::cout << "1 arg constructor called" << std::endl;

letters = new char[end - start + 1];
int i = start;

for (i = start; i < end; i++) {
    letters[i] = input[i];
}

letters[i] = '\0';

std::cout << letters << std::endl;
previous = NULL;
next = NULL;
}

What I cannot fathom is that the first time, this method is called, it works. Thereafter, it doesn't. Stepping through the debugger in Eclipse, the body of the for loop does not execute at all! I added

letters[i] = '\0'

to make sure that my array is null-terminated, makes no difference.

I have another method which takes in a pointer to the previous node in the linked list. I just omitted it

It seems like you don't actually want to index letters with i , since it begins at start . If start is greater than 0 , then you'll end up running over the end of the dynamically allocated array. Instead, you want:

letters[i - start] = input[i];

And then:

letters[i - start] = '\0'; // or end - start

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM