0

Been given a task to change my code to dynamic array. The program asks you to input array size 1 to 100. After that input vowels 1 by 1 with the normal array teikums[100]; it outputted the vowels and the vowel amount. Been given a task to make dynamic array without the "new". But after adding the dynamic array:

char *teikums = (char*)malloc(100);

It outputs blank space.

#pragma hdrstop
#pragma argsused

#include <string>
#include <tchar.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <iomanip>
#include <sstream>

using namespace std;

int main() {
  char *teikums = (char*)malloc(100);
  int c, i, count, patsk; // Patskani
  char yesno; // Atkartosanas Mainigais

  do {
    cout << " " << teikums[i];
    system("cls"); // Notira Ekranu
    do {
      patsk = 0; // Pieskir vertibu
      cout << "Input array size 1-100: ";
      cin >> count;
      if (count > 100 || count < 1) {
        cout << "Array cant be lower or higher than 0\n";

      }
    } while (count > 100 || count < 1);
    do {
      cout << "Input " << count << "letters one by one\n";
      for (i = 1; i <= count; i++) {

        cin >> teikums[i];
        if (!((teikums[i] >= 'a' && teikums[i] <= 'z') || (teikums[i] >=
          'A' && teikums[i] <= 'Z'))) {

          cout << "Error! Only input letters\n";
          i = i - 1;

        }
      }
    } while (i <= count);
    cout << "\nUsed Vowels:";
    for (i = 0; teikums[i] != '\0'; i = i + 2) {
      if (teikums[i] == 'a' || teikums[i] == 'e' || teikums[i] == 'i' ||
        teikums[i] == 'o' || teikums[i] == 'u' || teikums[i] == 'A' ||
        teikums[i] == 'E' || teikums[i] == 'I' || teikums[i] == 'O' ||
        teikums[i] == 'U') {
        ++patsk;

        cout << " " << teikums[i];
        teikums[i] = 0;
      }

    }

    cout << "\nVowel ammount: " << patsk;

    cout << ("\nDo you wish to continue(Y/Else):");

    // prasa lietotajam vai velas atkartot
    cin >> yesno;
    if (yesno == 'y' || yesno == 'Y') {

    }
    else {
      return 0;
    }
  } while (tolower(yesno) != 'n');
  getch();
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
AlexA
  • 13
  • 2

1 Answers1

0

In this line:

cout << " " << teikums[i];

i is not initialized and therefore it contains an indeterminate value.

This is causing all your troubles. But there may be other problems elsewhere, I didn't check all details.

If it worked with char teikums[100]; it's pure coincidence.

Google "C undefined behaviour" for more information.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115