c++: I want 2, 4, 6 to display... instead I think address numbers are displaying?
I want 2, 4, 6 to display... instead I think address numbers are displaying?
What do I need to do to correct and why? Thanks
(purpose... to demonstrate ability to change array space and still keep the base of the array)
int *line;
line = new int;
line[0开发者_如何学编程] = 2;
line = new int;
line[1] = 4;
line = new int;
line[2] = 6;
line = new int;
printf("%d %d %d", line[0], line[1], line[2]);
Try this instead:
int *line;
line = new int[3];
line[0] = 2;
line[1] = 4;
line[2] = 6;
printf("%d %d %d", line[0], line[1], line[2]);
delete[] line;
Points to notice:
line = new int[3]; // here you are supposed to specify the size of your new array
...
delete[] line; // whenever you use new sometype[somevalue];
// you must call delete[] later on to free the allocated resources.
Also take a look at this question in SO:
delete vs delete[] operators in C++
You're overwriting the pointer line
at each new int
. And you're leaking the memory from the one before it.
Also, since you're only allocating one int, only line[0]
is defined.
Accessing line[1]
and line[2]
is undefined.
You declare an int*
and allocate an int
with new
. At this point line
contains an address that points to the int
.
Accessing line[1]
and line[2]
are crashes waiting to happen because those locations contain garbage. You never allocated memory at those places.
Repeat after me: "This is not Java. I will not use new
without good reason."
For an array of three ints, you just want something like:
int line[] = {2, 4, 6};
To print them out, you normally want to use std::cout
instead of printf
:
std::cout << line[0] << " " << line[1] << " " << line[2];
Note, in particular, that there's no reason to use new
for this task at all.
The line line = new int
replaces the thing line
points to with a newly allocated piece of the stack of size int
.
精彩评论