You are allocating enough dynamic memory to hold an array of n
number of int
s, and then you are pointing p
at the 1st int
in that memory. So why wouldn't you expect the assignment to succeed? An int*
pointer can point at an int
.
But, you really shouldn't be using malloc()
(and scanf()
and printf()
) in C++ at all. C++ is not C, they are different languages, with different ways of doing things. Use new
(and std::cin
and std::cout
) in C++ instead:
#include <iostream>
int main() {
int n = 4, *p, s = 0;
p = new int[n];
std::cout << "\nEnter elements of array : ";
for(int i = 0; i < n; ++i) {
std::cin >> p[i];
s += p[i];
}
delete[] p;
std::cout << "\nSum : " << s;
return 0;
}
Or, in C++11 and later, you can use std::unique_ptr
to handle the delete[]
for you (and the new[]
in C++14 and later):
#include <iostream>
#include <memory>
int main() {
int n = 4, s = 0;
auto p = std::make_unique<int[]>(n); // C++14 and later
// std::unique_ptr<int[]> p(new int[n]); // C++11
std::cout << "\nEnter elements of array : ";
for(int i = 0; i < n; ++i) {
std::cin >> p[i];
s += p[i];
}
std::cout << "\nSum : " << s;
return 0;
}
However, whenever you need a dynamic array, you should prefer to use the standard std::vector
container instead. Let it handle the allocation and cleanup of the dynamic memory for you:
#include <iostream>
#include <vector>
int main() {
int n = 4, s = 0;
std::vector<int> p(n);
std::cout << "\nEnter elements of array : ";
for(int i = 0; i < n; ++i) {
std::cin >> p[i];
s += p[i];
}
std::cout << "\nSum : " << s;
return 0;
}
Though, in this particular case, you are not actually using the array for anything meaningful, so you can just get rid of the array completely, a single int
will suffice:
#include <iostream>
int main() {
int n = 4, v, s = 0;
std::cout << "\nEnter elements of array : ";
for(int i = 0; i < n; ++i) {
std::cin >> v;
s += v;
}
std::cout << "\nSum : " << s;
return 0;
}