Page 1 of 2 12 LastLast
Results 1 to 10 of 19
  1. #1
    Join Date
    Jun 2011
    Location
    Westerville, OH
    Posts
    9

    Question Dynamic Strings Question

    I'm still somewhat new to all this, so I've been following the C++ videos in order to learn what's what. I have a quick question involving the pointers and strings videos.

    After watching C-Style Strings, I decided to try to use pointers to dynamically accept input from the user (up to an absolute maximum of let's say... 50 characters). It's a small program I attempted for the sheer sake of learning.

    Here's the code...
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main() {
    	char *ptr = new char[10];
    
    	cout << "What's your name?" << endl;
    	cin.getline(*ptr, 50);
    	cout << "Hello, " << *ptr << endl;
    
    	delete[] ptr;
    
    	return 0;
    }
    It doesn't seem to like cin.getline(*ptr, 50); and won't compile. Apparently I'm changing data types (char to char* I think) and I'm not sure how to get around that. I know I can't just put ptr there, even though it will run, because that's just the pointer and not where the array is.

    Any idea what's wrong?

  2. #2
    Join Date
    Oct 2005
    Location
    Seattle, WA
    Posts
    501
    Just to be clear, a pointer is an address in memory. It is declared using the *.
    Code:
    char *ptr = new char[50];
    Here ptr holds the address where a char array is stored. Using the * on a pointer after it is declared is called dereferencing. What is returned is the value of the data type stored at that address. In this case you would get a char not a char*.
    Code:
    cin.getline(ptr, 50);
    This is correct. Also, If you are planning on reading in 50 chars make sure your array is large enough to hold it!

  3. #3
    Join Date
    Jun 2003
    Posts
    150
    You'll actually need to make the array 51 characters wide as cin.getline() takes upto n-1 and puts a null terminator on the end to make sure the string is null terminated(basically so other things know they've reached the end of the string without the need to know how big the string is).

    Another thing you'll want to be aware of is cout << "Hello, " << *ptr << endl; will only print the first character in the string as the dereference (*ptr) is basically saying ptr[0].

  4. #4
    Join Date
    Jun 2011
    Location
    Westerville, OH
    Posts
    9
    Thanks for the reply!

    Okay so I see now that using ptr does work, assuming the input data is small enough for the array to hold. I assumed I had to dereference the pointer before I could input the given string there. Also, I had tried using ptr before, but assumed it didn't work because I was using too many characters.

    However, this presents a different problem. From the start I wanted to have an array that could add slots depending on the input, so I had it start as a size of 10 and created it within the heap, thinking it might be able to dynamically adjust the size accordingly. The video said it could, but I guess I'm unsure of how that's suppose to work. That or I misunderstood it.

    On the other hand, I'm seeing that Linked Lists are probably what I was going for from the start, so my approach is wrong? A linked list could continually add to the size of the array.

    How about this, if you were to allow the input of someone's name, how would you store that name in an array that would adjust its size accordingly to the name itself.
    I can't figure it out because I'm trying to declare the array, and therefore declare its size, before knowing how long the name actually is.

  5. #5
    Join Date
    Jun 2011
    Location
    Westerville, OH
    Posts
    9
    Thanks, I forgot *ptr would only show the first letter.

    And the goal isn't to have an array of 50, that was just a sort of random limit I had in mind.
    But yes, if I were to actually store 50 characters, it would need to be 51 there.

  6. #6
    Join Date
    Jun 2003
    Location
    Trier, Germany
    Posts
    1,350
    Quote Originally Posted by Zelosh View Post
    From the start I wanted to have an array that could add slots depending on the input, so I had it start as a size of 10 and created it within the heap, thinking it might be able to dynamically adjust the size accordingly. The video said it could, but I guess I'm unsure of how that's suppose to work. That or I misunderstood it.
    You got the right idea there. When processing input, you only read small chunks of input into a fixed size buffer and then concatenate them into their final storage whenever the buffer overflows or the input is completed. You could implement this yourself with a loop over getline(). Note that cin already uses a buffer under the hood, so there's usually no need for you to add another layer of buffering if you use all of cin's capabilities (although that is not necessary for now, so feel free to go on with your original idea).

    On the other hand, I'm seeing that Linked Lists are probably what I was going for from the start, so my approach is wrong? A linked list could continually add to the size of the array.
    A linked list would do the job, but it's not the most efficient or elegant solution. What you want is a dynamically growing array: You start with an arbitrary sized array and fill it up. Whenever you run out of space, you allocate a second array two times the size of your original array, copy your data from the original array to the new array and eventually delete the original one afterwards. Then you assign your pointer from the deleted array to the new one and can happily resume reading data.

    This is such a fundamental concept in C++ that the standard library already ships with a class that implements just that behavior: std::vector. In real-life code, that would be the right tool for this job.
    But since you are just playing around for the purpose of learning: See if you can implement such a growing array yourself.

  7. #7
    Join Date
    Mar 2009
    Location
    Bellevue, WA
    Posts
    803
    Building on what ComicSansMS said about creating a DynArray (dynamic array) be sure that you don't just set your newly allocated array equal to the old array using the assignement operator unless you had a class and then wrote the code to handle it with an overloaded assignment operator which you will learn later.

    For now you can just use a for loop or a while loop and aftern dynamically allocating your new array(double the size of the old array) loop through copying over each element from the old array into the new array. For example you could add a function that checks if your array has reached maxium capacity each time a new element is added and have it return a boolean value and if say the next item to be added will put it over the max create a new array double the size, copy over the old array and then add the new value.

    Most of this goes beyond what you were asking but again I was just building off of ComicSans comment. This is definitely good practice and data structures are a huge part of a programmers job, most interview questions at companies are based around data structures and manipulating them.
    " Imagination is the preview of life's coming attractions " - Albert Einstein
    " If you can't explain it simply, you don't understand it well enough." - Albert Einstein

    My Website: http://www.gamedevlounge.com/

    If any post is informative please provide positive feedback by clicking the star below.

  8. #8
    Join Date
    Jun 2003
    Posts
    150
    You know I spent the last hour writing up an explanation on how to make and use linked lists and I was going to state at the end to be familiar with the concept of linked lists and pretty much never use them this way (creating them by using pointers and such) and then explain the concept of std::vectors. Problem was I kept wanting my linked lists do to new things and such and got side tracked. My brain first decided it wanted to take a ride on Recursion River, forgetting the fact that we were dealing with lists not trees. Then it wanted to a bunch of gobbly gook on like traversal in both directions and removing all instances of a value and what not. I'm at least glad I wrote it using just functions instead of wrapping it up in class because we would have headed down a whole bunch of different roads there.

    Here's the gist of why not to use them the 'create and link by pointer/address' way.

    While Linked Lists are neat and actually are useful in certain circumstances in their behavior(the ability to dynamically shrink and grow), implementing them the way they are usually taught(through use of pointers) is highly inefficient because your data is fragmented all over your memory, causing a lot of cache misses because they are not next to each other in memory. In addition accessing a value in a linked list is slow because you have to iterate and compare through every node until you reach the node you're looking for. Whereas an array is a simple multiplication of the index number times the size of a single element added onto the address of the first element of the array.

    You can use the concept of a linked list however to do some neat stuff such as specifying a different order to an array without actually rearranging it. If you create an array of index numbers you can then rearrange just that list of indices and just "iterate" through the array with that index list order.
    Last edited by Edge Damodred; 04-06-2012 at 07:13 PM.

  9. #9
    Join Date
    Mar 2009
    Location
    Bellevue, WA
    Posts
    803
    In terms of searching an array it would be faster than say a linked list but when working with larger amounts a data a linked list would be preferred over a dynamic array. This is due to the nature of dynamic arrays needing to be doubled in size when reaching max capacity. When it reaches max capacity I have to allocate a new array, copy over the old data and then add a new element. With a linked list you never have to worry about this issue it takes the same amount of time each time I add a new element.
    " Imagination is the preview of life's coming attractions " - Albert Einstein
    " If you can't explain it simply, you don't understand it well enough." - Albert Einstein

    My Website: http://www.gamedevlounge.com/

    If any post is informative please provide positive feedback by clicking the star below.

  10. #10
    Join Date
    Jun 2011
    Location
    Westerville, OH
    Posts
    9
    Dizzy... I'm a little dizzy
    but I think I get it!

    I'll post whenever I've figured it out based on what ComicSan and Kwest have said. Thank you guys so much!!!!! You've really answered what I was confused about. I just need to go work on it now~ ^^

    Quote Originally Posted by Kwest View Post
    Most of this goes beyond what you were asking but again I was just building off of ComicSans comment. This is definitely good practice and data structures are a huge part of a programmers job, most interview questions at companies are based around data structures and manipulating them.
    In the meantime, could you elaborate on "data structures"? I pretty much get what you mean through intuition, but I'd like to know what all is encompassed by that term. If it is such an important concept, I'd like to have a full understanding of it, so anything, even a link or something, would be helpful.

    I could also just look it up on wikipedia.... that might work xD

Page 1 of 2 12 LastLast

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •