d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Rather Long C++ Pointer Assignment - Help!
12Next
Add Reply New Topic New Poll
Member
Posts: 950
Joined: Feb 19 2009
Gold: 2,595.00
Sep 23 2013 07:57am
I am not too familiar with pointers and structs (I've been reading about it but it's still not clicking completely). This assignment involves writing missing code for functions and if someone could help me out with them, greatly appreciated. I'm definitely trying to learn this so some form of explanation would also be very helpful! thanks again!

Code
/*
* Topics: Multidimensional Arrays, Pointers, Dynamic Allocation, Structs
*
*/
#include <iostream>
#include <cstring>
#include <string>
using namespace std;


/* Globally defined constants
*/
const int MAX_WORD_SIZE = 20;


/* Words structure
*
* This has three member variables list: which will contain a list
* of cstrings, size: the max number of words the list can store and
* num_words: the number of cstrings in list.
*/

struct Words {
unsigned int num_words; // Number of words currently in list
unsigned int max_words; // The total size allocated to the list.
char **list; // The list storing the words
};



/* Function prototypes:
* To be implemented
*/

Words * newList(const unsigned int max_words);
Words * newList(const char words[]);
int deleteList(Words *p_w);
int printList(Words *p_w);
int appendList(Words *p_w, const char words[]);
int appendList(Words *dst, const Words *src);
char* findWord(const Words *p_w, const char word[]);
int removeWord(Words *p_w, const char word[]);



/* Main function
*
* Note the newList and deleteList functions must be implemented before appendList so the
* calls to appendList are initally commented out.
* Your code should work with the main below. Including the appendList functionality that is initially commented out.
*/


int main()
{
Words *pokemon, *tb;
char *word;
int ok=0;
string poke="charmeleon mewtwo pikachu charmander squirtle caterpie raichu butterfree abra kadabra alakazam slowpoke spoink"; //declaring a string
char team_a[]="rayquaza mew snorlax"; //creating array c_string
string team_b="weavile shuckle ampharos toxicroak mrmime";



cout << poke.c_str() << endl;
pokemon=newList(5); // Words * newList(const unsigned int max_words);
ok=deleteList(pokemon); // int deleteList(Words *p_w);
cout << "OK? "<< ok << endl;
pokemon=newList(poke.c_str()); // Words * newList(const char words[]);
tb=newList(team_a); // Words * newList(const char words[]);
cout << "*pokemon"<< endl;
printList(pokemon); // int printList(Words *p_w);
cout << "*tb"<< endl;
printList(tb); // int printList(Words *p_w);
/*
//
// Note the newList and deleteList functions must be implemented before appendList so the
// calls to appendList are initally commented out.

ok=appendList(tb,team_b.c_str()); // int appendList(Words *p_w, const char words[]);
cout << "*tb"<< endl;
printList(tb); // int printList(Words *p_w);

ok=appendList(pokemon,tb); // int appendList(Words *dst, const Words *src);
cout << "*pokemon"<< endl;
printList(pokemon); // int printList(Words *p_w);
word=findWord(pokemon,"charmeleon"); // char* findWord(const Words *p_w, const char word[]);
cout << "*word "<< *word << " word " << word << " address " << &amp;word << endl;
ok=removeWord(pokemon,"squirtle"); // int removeWord(Words *p_w, const char word[]);
cout << "*pokemon"<< endl;
printList(pokemon); // int printList(Words *p_w);
*/
return 0;
}

/* Function: newList
*
*
* Takes the max_words of the list and creates a new Words
* with the given max_words without assigning any words, sets
* num_words to zero. returns the new list to the calling function.
* max_words must be greater than zero, otherwise newList returns
* NULL.
*/

Words * newList(const unsigned int max_words)
{
if(max_words < 1)
return NULL;

// Allocate list
Words * p_w = new Words;

// FUNCTION CODE GOES HERE

return p_w;

}

/* Function: newList
*
* Overloaded version of newList, this one takes a character
* array with words separated by spaces, for example:
*
* "charmeleon mewtwo pikachu charmander squirtle caterpie raichu butterfree abra kadabra alakazam slowpoke spoink"
*
* has four words. This newList will allocate enough space
* for the words, then the list will be initialized to those
* words and returns the list to the calling function. If
* words is empty, newList does nothing and returns NULL.
*/

Words * newList(const char words[])
{
// duplicate the words to handle literal input
char *dup = strdup(words);
int len = strlen(dup);

//Can't allocate zero memory
if(len == 0)
return NULL;

Words *p_w = NULL;

// FUNCTION CODE GOES HERE

return p_w;
}

/* Function: deleteList
*
* Takes a dynamically allocated Words and deletes
* the list and then the Words itself, returns 0.
* If the Words is NULL deleteList does nothing and
* returns -1;
*/

int deleteList(Words *p_w)
{
if(p_w == NULL)
return -1;

// FUNCTION CODE GOES HERE

return 0;

}

/* Function: printList
*
* Prints the words in the Words on a single Line
* with a single space between words. There is no
* space after the last word, but there is a newline,
* returns 0 for successful print. If p_w is NULL,
* printList does nothing returns -1.
*/

int printList(Words *p_w)
{
if(p_w == NULL)
return -1;

// FUNCTION CODE GOES HERE

return 0;
}

/* Function: appendList
*
* Takes a Words and a character array consisting of words
* separated by spaces, for example:
*
* "charmander squirtle caterpie raichu"
*
* Contains four words. appendList will take the Words
* and append these words to list. If the Words does not
* have enough space, appendList will dynamically allocate
* more space to list to allow these new words to fit.
* Returns the number of words appended. If words is empty
* or if p_w is NULL then appendList does nothing and returns -1.
*/

int appendList(Words *p_w, const char words[])
{
// duplicate the words to handle literal input
char *dup = strdup(words);
int len = strlen(dup);

if(p_w == NULL || len == 0)
return -1;

int word_count = 0;

// FUNCTION CODE GOES HERE

return word_count;
}

/* Function: appendList
*
* Takes two Wordss, appends the contents of src
* to dst. If dst does not have enough space
* appendList should dynamically allocate additional space
* then append the contents of src to dst, returns
* 0 on success. If either Words is NULL appendList does
* nothing and returns -1.
*/

int appendList(Words *dst, const Words *src)
{
if(dst == NULL || src == NULL)
return -1;

// FUNCTION CODE GOES HERE

return 0;
}

/* Function: findWord
*
* Finds the first occurrence of the word in the Words
* returns a pointer to that word in the list. Otherwise
* returns NULL. If p_w is NULL return NULL
*/

char* findWord(const Words *p_w, const char word[])
{

// FUNCTION CODE GOES HERE

return NULL;
}


/* Function: removeWord
*
* If p_w is null, returns -1. Otherwise, searches for every
* occurrence of word[], and removes that word of the list, returns
* the number of words removed.
*
*/

int removeWord(Words *p_w, const char word[])
{
int num_removed = 0;
if(p_w == NULL)
return -1;
else
{
num_removed++;

}

return num_removed;
}


/*in c++, the arrow operator is used to access number variables and function when using a pointer
to an object and the dot operator when accesing objects directly
example

Words *pokemon, poke;

pokemon ->list //pointer acess
*(pokemon) ->list//pointer access

poke.list // object access
/*/
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Sep 23 2013 10:43am
where are you having problems?
Member
Posts: 950
Joined: Feb 19 2009
Gold: 2,595.00
Sep 23 2013 10:55am
Quote (carteblanche @ Sep 23 2013 11:43am)
where are you having problems?


i'm just not sure how to manipulate the list of words using the pointers and struct.. like would Words *newList be calling the pointer to the function newList?

Code
/* Function: newList
*
*
* Takes the max_words of the list and creates a new Words
* with the given max_words without assigning any words, sets
* num_words to zero. returns the new list to the calling function.
* max_words must be greater than zero, otherwise newList returns
* NULL.
*/

Words * newList(const unsigned int max_words)
{
if(max_words < 1)
return NULL;

// Allocate list
Words * p_w = new Words;

// FUNCTION CODE GOES HERE

return p_w;

}


that for example, i'm not sure how to use Words to do the requirements and also slightly confused on the * p_w.. why the *?.. would it be something along the lines of:

Words * p_w = new Words;
p_w.max_words = max_words; //bringing in the maxwords from the original list
p_w.num_words = 0;
return p_w;

edit: nvm that one worked i believe... the other newlist that confused me..

Code
/* Function: newList
*
* Overloaded version of newList, this one takes a character
* array with words separated by spaces, for example:
*
* "charmeleon mewtwo pikachu charmander squirtle caterpie raichu butterfree abra kadabra alakazam slowpoke spoink"
*
* has four words. This newList will allocate enough space
* for the words, then the list will be initialized to those
* words and returns the list to the calling function. If
* words is empty, newList does nothing and returns NULL.
*/

Words * newList(const char words[])
{
// duplicate the words to handle literal input
char *dup = strdup(words);
int len = strlen(dup);

//Can't allocate zero memory
if(len == 0)
return NULL;

Words *p_w = NULL;

// FUNCTION CODE GOES HERE

return p_w;
}


why are we bringing in the char words[]? im confused as to what exactly are we bringing in and how we are suppose to use to create a newList with the same exact items inside


This post was edited by falco37 on Sep 23 2013 11:09am
Member
Posts: 950
Joined: Feb 19 2009
Gold: 2,595.00
Sep 24 2013 08:03pm
i've made some leeway and now running into another error.

Code
Words * newList(const char words[])
{
// duplicate the words to handle literal input
char *dup = strdup(words);
int len = strlen(dup);

//Can't allocate zero memory
if(len == 0)
return NULL;

Words *p_w = NULL;
for (int i =0;i<len;i++) //for loop to count the number of spaces
if (dup[i]==' ') //with knowing number of spaces, you know that there is 1 more word than space
spaceCount++;
char **list;
new char*[p_w->max_words];
list = new char*[p_w->max_words];

for (int i=0;i<len;i++)
{
if (words[i] != ' ')
wordLength ++;
else
string word1 = dup.substr (wordBegin,wordLength);
wordBegin = i+1;
list[i] = new char[max_word_length];


}
return p_w;
}


im getting error: request for member 'substr' in 'dup' which is of non-class type 'char**'

Member
Posts: 237
Joined: Aug 6 2011
Gold: 6,026.00
Sep 24 2013 10:05pm
new char*[p_w->max_words]; -> this line is useless, besides creating a memory leak

Quote
else
            string word1 = dup.substr (wordBegin,wordLength);
            wordBegin = i+1;
            list[i] = new char[max_word_length];


What's going on here? All the code beyond the else should be scoped in like this:

Quote
else
      {
            string word1 = dup.substr (wordBegin,wordLength);
            wordBegin = i+1;
            list[i] = new char[max_word_length];
      }


Now for the errors, I don't see what purpose word1 serves as it dies when you exit the scope. As for dup.substr, you just can't do that. dup is char*, not a string class. There's a few ways to go shortening dup.

First way:
string word1 = dup;
word1.substr(wordBegin, wordLength);

Second way:
dup += wordBegin;

Third way:
char *dup_short = (char*)malloc(wordLength - wordBegin +1);
strcpy(dup_short, dup +wordBegin);

This post was edited by flyinggoat on Sep 24 2013 10:05pm
Member
Posts: 950
Joined: Feb 19 2009
Gold: 2,595.00
Sep 24 2013 10:17pm
Code
Words * newList(const char words[])
{
int spaceCount = 0;
int wordBegin = 0;
int wordLength = 0;
int wordCount = 0;

// duplicate the words to handle literal input
char *dup = strdup(words);
int len = strlen(dup);

//Can't allocate zero memory
if(len == 0)
return NULL;

Words *p_w = NULL;
p_w = new Words;
for (int i =0;i<len;i++) //for loop to count the number of spaces
if (dup[i]==' ') //with knowing number of spaces, you know that there is 1 more word than space
spaceCount++;
p_w->list = new char*[p_w->max_words];
for (int i=0;i<(spaceCount+1); i++) //words on the list will be number of spaces + 1
p_w->list[i] = new char[MAX_WORD_SIZE];

string dupStr = (string)dup;

for (int i=0;i<len;i++)
{
if (words[i] != ' ')
wordLength ++;
else
{ string word1 = dupStr.substr (wordBegin,wordLength);
wordBegin = i+1;
char * localStr = new char[word1.length() + 1];
strcpy(localStr, word1.c_str());
p_w->list[i] = localStr;
wordLength = 0;
delete [] localStr;
}
}

return p_w;
}


is what i came up with for this newList and it seems to be compiling just fine.. i'm having issues now with the print list however..

Code
int printList(Words *p_w)
{
if(p_w == NULL)
return -1;

for (int i=0;i<p_w->num_words;i++)
cout << p_w->list[i] << " ";

return 0;
}


its printing #(random letter) 10 times and then it goes to copying part of the next line...
Member
Posts: 237
Joined: Aug 6 2011
Gold: 6,026.00
Sep 24 2013 10:37pm
Quote

          wordBegin = i+1;
            char * localStr = new char[word1.length() + 1];
            strcpy(localStr, word1.c_str());
            p_w->list[i] = localStr;
            wordLength = 0;
            delete [] localStr;


dump the delete[]. What you are doing is creating localStr, giving it some memory with new, assigning p_w->list[i] address to localStr address, then... deleting localStr. What do you expect p_w->list[i] to point to now?

You're mixing the notion of pointer and allocated memory. A pointer is like any other type defined, it lives within a scope dies outside of it. You don't go around assigning ints and then expecting to have to use delete on them, do you? Same with pointers. What you use delete on is the memory you allocated with new and point to with your pointer. That memory lives on as long as the software is running, so you need to dispose of it once you're done with it. However you're not done with until you're done outputting it and whatever else you need to do with it.
Member
Posts: 950
Joined: Feb 19 2009
Gold: 2,595.00
Sep 25 2013 08:11am
Quote (flyinggoat @ Sep 24 2013 11:37pm)
dump the delete[]. What you are doing is creating localStr, giving it some memory with new, assigning p_w->list[i] address to localStr address, then... deleting localStr. What do you expect p_w->list[i] to point to now?

You're mixing the notion of pointer and allocated memory. A pointer is like any other type defined, it lives within a scope dies outside of it. You don't go around assigning ints and then expecting to have to use delete on them, do you? Same with pointers. What you use delete on is the memory you allocated with new and point to with your pointer. That memory lives on as long as the software is running, so you need to dispose of it once you're done with it. However you're not done with until you're done outputting it and whatever else you need to do with it.



ahh i see.. yeah that makes alot more sense.. i tried running the code without the delete and it gives me this:



so basically its running through print list until it finishes the word but for some reason it is crashing right after.. i'm not sure why
Member
Posts: 237
Joined: Aug 6 2011
Gold: 6,026.00
Sep 25 2013 08:18am
Looks like it's trying to output 14 words (0 through 13) and I only see 13 words inputed
Member
Posts: 950
Joined: Feb 19 2009
Gold: 2,595.00
Sep 25 2013 08:51am
Quote (flyinggoat @ Sep 25 2013 09:18am)
Looks like it's trying to output 14 words (0 through 13) and I only see 13 words inputed


hmm but the thing is it only printed out the first word which is charmeleon.. maybe where i have
Code
for (int i=0;i<p_w->num_words;i++)
cout << p_w->list[i] << " ";


since num_words is only 13, it is stopping there... should i implement a for loop before to count the total number of characters in the whole list instead?

This post was edited by falco37 on Sep 25 2013 08:51am
Go Back To Programming & Development Topic List
12Next
Add Reply New Topic New Poll