Dynamic string array

Posts 1–3 of 3 · Page 1 of 1
Dynamic string array
Hello , I am learning c++ and I am learning pointer atm.. I would like to make a dynamic array that contain password of each students in class ( for example ) But instead of doing it with const , I would like to know how to do it with pointer ? I want to ask how much students will be in this class , then ask the password for each students , please help me !

Here an example of what I want it to look like :

Keep in mind I didnt learn class yet show me a simple way to do it

Code:
#include <iostream>
#include <Windows.h>


using namespace std;


int main()
{
	
	
	 

	int students = 0;

	cout << "How much students are you in your class ?" << endl;
	cin >> students;

	string _students[students];

	

	for (int i = 0; i != students; i++)
	{

		cout << "Students : " << i << endl;
		cin >> _students[i];
	

	}
	
		
	for (int i = 0; i != students; i++)
	{

		cout << "Students passwords : \n" << endl;
		cout << i << "  " << endl;
		cout << _students[i];

	}
	
	return 0;
}
Code:
// Header
#define MAX_PASSWORD_LENGTH  64

// Global pointer
char* passwords;

// Gets the password
char* GetPassword( int id ){
   if( passwords ){
        return ( char* )( passwords + ( id * MAX_PASSWORD_LENGTH ) );
   }
   return ""; // No allocated buffer
}

// Sets the password
void SetPassword( int id, char* password ){
    strcpy_s( ( char* )( passwords + ( id * MAX_PASSWORD_LENGTH ) ), MAX_PASSWORD_LENGTH, password );
}

// In main
int nStudents = 10; // Number of students ( cin or whatever )

// Allocate the dynamic buffer
passwords = HeapAlloc( GetProcessHeap(), nStudents * MAX_PASSWORD_LENGTH, HEAP_ZERO_MEMORY ); // Allocated dynamic buffer
char tmp[MAX_PASSWORD_LENGTH];

// Save the passwords for each
for( int i=0; i<nStudents; i++ ){
    cin >> tmp;
    SetPassword( i, tmp );
}

// Output each password
for( int i=0; i<nStudents; i++ ){
    cout << " [ " << i << " ]: " << GetPassword( i );
}

// At the end of the program free the buffer
HeapFree( GetProcessHeap, NULL, passwords );
Thank you
Posts 1–3 of 3 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Talk with us