What do you all think of this method for declaring an array dynamically?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;

string str;
int size;
char ch;

int main()
{
    printf("Enter a string: \n");
    do{
        scanf("%c", &ch);
        str += ch;
        ++size;
    }while (ch != '\n');

    {
        char charray[size];
        for (int i = 0; i < size; ++i)
            {
                charray[i] = str[i];
            }
        cout << "str = " << str << " " << endl;
        cout << "charray = ";
        for (int i = 0; i < size; ++i)
            {
                cout << charray[i];
            }
        cout << endl << endl;
    }



    return 0;
}


I was just wondering is there anything flawed with it? I'm new to using printf and scanf so just wanted to make sure.
I wander why you are using both streams and C functions for I/O.

In this program you are not creating a dynamic array.
char charray[size]; is not supposed to work as 'size' is not constant.
If your program works, your compiler is not behaving in a standard way.
well i'm using mingw compiler with codeblocks. i guess maybe its not supposed to work, but it does. and I ain't complaining. How else would you create an 'dynamic' array without knowing before hand how big it would be? By dynamic I mean memory is allocated for it at runtime because it is not known what 'size' is going to be at compile time.
If I shouldn't do it in this way then how should I?

And btw, I was using the streams for debugging purposes only as I didn't want to have to take the time to write out a loop to print strings. and yeah yeah yeah i shouldn't use strings in a c program either right?
The way to allocate dynamic arrays in C++ is using new:
1
2
3
char *charray = new char[size];
//use it...
delete[] charray; // free the memory 


If you are using C, you need to use malloc:
1
2
3
char *charray = (char*) malloc (size);
//use it...
free (charray); // free the memory 


Notice that if you are using this to have C strings, you need size to be large enough to hol the string characters an '\0' to terminate the string.
Topic archived. No new replies allowed.