I still dont understand pointers and references really. I found this segment of code somewhere on the forums. I was trying to convert it to a function to help learn how to dynamically allocate an array.
I think i understand somewhat whats going on, but what confuses me is its all in main, so the size of the array is known, and automatically makes me think of just making int var[10]; instead. so i figured if i just make it to a function i could see the value in it.
I was trying to make it something like this:
1 2 3
int * array;
array = make_array_size_of(10);
cout << "last index is" << array[9];
I know something like vector can make an unknown array size, but i havent learned it yet. So is the way possible or must i learn vectors to accomplish this?
Arrays allocated using new[] must be deleted using delete[], not delete.
I know something like vector can make an unknown array size, but i havent learned it yet. So is the way possible or must i learn vectors to accomplish this?
Yes, you can do it using dynamic allocation. vectors do something similar internally.
/home/metulburr/Documents/cplusplus/Tutorial/main.cpp||In function ‘int make_array_size(int)’:|
/home/metulburr/Documents/cplusplus/Tutorial/main.cpp|13|error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]|
/home/metulburr/Documents/cplusplus/Tutorial/main.cpp||In function ‘int main()’:|
/home/metulburr/Documents/cplusplus/Tutorial/main.cpp|18|error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]|
created array[0]
created array[1]
created array[2]
created array[3]
created array[4]
created array[5]
created array[6]
created array[7]
created array[8]
created array[9]
created array[10]
created array[11]
created array[12]
created array[13]
created array[14]
created array[15]
created array[16]
created array[17]
created array[18]
created array[19]
Segmentation fault
EDIT2:
so then i made a print statement after the function call and before the print of the index of a, in which that didnt print out, so the problem must be wit returning the array back to a? Im just not sure why?
ooooooooooh ok i get it, the function also has be *make_array_size(int size)
Iwasnt even thinking about the function header at all for some reason
thanks EssGeEich, that led me to the fix.