0

I am having some trouble storing some char pointers in my array

The method should take a char* array and and int pointer which is the size of the array. Then I loop and ask the user to enter the names. Then I want to print them; however it seems like there's nothing in my array.

Note I cannot use array notation for this assignment, I must use pointer notation to access the elements of the array.

void sort_name(char* name[], int* items)
{
  //store the names
    cout << "In function items is " << *items << endl;

    for(int i=0; i<*items; i++)
    {
        string str;
        cout << "Enter name #" << (i+1) << ": ";
        getline(cin, str);

        char* current = new char[str.size() + 1];
        *(name + i) = current;
    }

    for(int i=0; i<*items; i++)
    {
        cout << *(name + i) << endl;
    }



}
1
  • oh that's right. one for those mental farts. sorry about such an easy question. after a while a programming i can't think that straight. always need a second pair of eyes. Commented Nov 5, 2011 at 21:54

5 Answers 5

4
    char* current = new char[str.size() + 1];
    *(name + i) = current;

You are correctly allocating new memory for each of the array elements, but you never assign any value to them. Since this is homework, I won't say more.

Sign up to request clarification or add additional context in comments.

Comments

1

You forgot to copy the string entered by the user to the array. There is no copy from str to current.

Comments

0

You need to actually copy the string, rather than just allocate space for a copy. Try this:

int length=str.copy(current,str.size(),0);
current[length]='\0';

just after you allocate the string. I.e., put the above code right after this line in your code:

char* current = new char[str.size() + 1];

Comments

0

If you want to do this way you need to copy the actual entry.
check strcpy or memcpy.

Comments

0

add the second line : (and #include "stdio.h")

char* current = new char[str.size() + 1];
strcpy(current , str.c_str());
(name + i) = current;

it should work.

You use "int* items", its better to use "int items". i would written "name[i]" instead of "*(name + i)". and if you know the maximum size of strings you want to allow, if it's n, you can directly write :

for(int i=0; i<*items; i++)
{   
   cout << "Enter name #" << (i+1) << ": "; 
   name[i] = new char[n];
   cin.getline( name[i] , n);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.