I can not enter the data for arrays - c++

I want to enter n times values for c and e arrays. The following program doesn't allow me to even enter the value of 'n'. Could you tell me where is the mistake?
#include <iostream>
using namespace std;
int main()
{
int n,c[n],e[n];
cin>>n;
for(int i=0;i<n;i++){
cin>>c[i]>>e[i];
}
return 0;
}

"n" should be defined before using it to fix array size. Also, const int or constant should be used to declare array size not plain int.
In order to use plain datatype, you can initialize array dynamically like
vector<int> a(n); or
int a = new int[n]

int n,c[n],e[n];
This declaration creates arrays c and e on stack with random size, because n as an automatic variable is initialized with random value. Instead you need to dynamically create arrays on heap or use std::vector.
Example:
#include <iostream>
#include <vector>
using namespace std;
int main() {
// your code goes here
int n;
vector<int> v;
std::cin >> n;
v.resize( n);
for( int i = 0; i < n; ++i) {
cin >> v[i];
}
for( int i = 0; i < n; ++i) {
cout << v[i];
}
return 0;
}
http://ideone.com/QhgfNv

In the line of
int n,c[n],e[n];
Computer don't know the exact value of 'n', so it can't alloc memory of array.
The simplest solution is create array with fixed number, and check n after you know the value of n as follows:
int n, c[1024], e[1024];
cin >> n;
if (n > 1024) { /* error */ }
The other way is malloc memory after u know the value of n:
int n;
cin >> n;
int *c = new int[n];
int *e = new int[n];
xxxx
delete [] c;
delete [] e;

You can try something like this:
#include <iostream>
using namespace std;
int main()
{
int temp = 100; /*Random value*/
int c[temp];
int e[temp];
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>c[i]>>e[i];
}
return 0;
}
Now, I chose temp as 100, but you can do big as your int can store. Now, if n is lower than temp, your for cycle will let you save your values without troubles.

Related

How to copy char array of a structure into another char array of a structure?

#include <iostream>
using namespace std;
struct stud
{
char name[10];
int id;
};
int input(stud a[], int size)
{
for(int i=1; i<=size; i++)
{
cout<<"name = ";
cin>>a[i].name;
cout<<"id = ";
cin>>a[i].id;
}
cout<<endl;
return 0;
}
int output(stud a[], int size)
{
for(int i=1; i<=size; i++)
{
cout<<"name = "<<a[i].name<<" ";
cout<<"id = "<<a[i].id<<" ";
}
cout<<endl;
return 0;
}
int copy(stud a[], stud x[], int size)
{
for(int i=1; i<=size; i++)
{
x[i].name=a[i].name;
x[i].id=a[i].id;
}
output(x,size);
cout<<endl;
return 0;
}
int main()
{
struct stud s[3], x[3];
input(s,3);
output(s,3);
copy(s,x,3);
return 0;
}
In this program the statement in function copy x[i].name =a[i].name; is not copying contents from 1 structure object to another. I have tried to put this statement in for loop for(int j=1;j<=10;j++) x[i].name[j] =a[i].name[j]; but still not working.
please suggest what should be changed or some alternatives for this.
i'll be very thankful to you for this.
regards,
umar
Either using a loop to copy each character in the name field or using thestrcpy function from <cstring> header works.
int copy(stud a[], stud x[], int size) {
for(int i = 1; i <= size; i++) {
// for(unsigned j = 0; j < 10; j++) {
// x[i].name[j] = a[i].name[j];
// }
strcpy(x[i].name, a[i].name);
x[i].id = a[i].id;
}
output(x, size);
cout << endl;
return 0;
}
But since you tagged this as c++, consider using std::string instead of a char array, unless you have a particular reason for using a char array. In that case x[i].name = a[i].name would have worked just fine and you could also use the standard algorithm library for copy. Also, using std::array instead of a raw C array for you "array of structures" might be a better option (does not degenerate into a pointer like a regular C array does).
Evrey single one of your loops is wrong, because in C++ arrays start at zero. So not
for(int i=1; i<=size; i++)
instead
for(int i=0; i<size; i++)
You cannot copy arrays by writing a = b;. Since your arrays are really strings there's a built in function strcpy to copy strings.
strcpy(x[i].name, a[i].name);
If you use = to copy struct, the char array inside that struct will be copied. You don't need to do anything more.
#include <iostream>
using namespace std;
typedef struct{
char name[10];
} type_t;
int main() {
type_t a = {"hihi"};
type_t b;
b = a;
a.name[0] = 'a';
cout<<a.name<<endl;
cout<<b.name<<endl;
return 0;
}
output:
aihi
hihi
ideone: https://ideone.com/Zk5YFd

I am trying to pass an DMA array and its size as an argument but it is giving an error

I am trying to pass a dynamic memory allocated array and its size to a function 'sum' but it is giving error of permissive what should I do?
#include<conio.h>
#include<iostream>
using namespace std;
int sum(int n[], int *m)
{
for(int z=0;z<*m;z++)
{
cout<<"\n the output is = "<<n[z]<<"\n";
}
}
int main()
{
int *n,*m,a; //declaration is done here**strong text**
cout<<"enter the size of array = ";
m=new int;
cin>>*m;
n=new int[*m];
for(int i=0;i<*m;i++)
{
cout<<"\n enter the "<<i+1<<" array = ";
cin>>n[i];
cout<<"\n";
}
/* for(int z=0;z<*m;z++)
{
cout<<"\n the output is = "<<n[z]<<"\n";
}*/
int sum(n,&m);//here "m" is an pointer and I am trying to pass int in a function with an array
return 0;
}
Your code should, probably, look like the following (Linux Ubuntu + gcc):
#include <iostream>
using namespace std;
int sum(int n[], int m)
{
int s=0;
for(int z=0; z<m; z++)
{
cout<<"\n array["<<z<<"]= "<<n[z]<<"\n";
s+=n[z];
}
return s;
}
int main()
{
int *n,m;
cout<<"enter the size of array = ";
cin>>m;
n=new int[m];
for(int i=0; i<m; i++)
{
cout<<"\n enter array["<<i+1<<"] value = ";
cin>>n[i];
cout<<"\n";
}
int s = sum(n, m);
cout<<"s="<<s<<endl;
return 0;
}
There is no use allocating the size of the array m dynamically. It is an ordinary int variable and can be initialized as
cin>>m;
You may also write the sum prototype in the form
int sum(int * n, int m)
It is another way of passing a 1-dimensional array as a function parameter.
Speaking frankly, these questions are the very basics of the language.
You should, probably, read something like
Dynamic memory allocation/dynamic arrays
about dynamic memory allocation and dynamic arrays and
Simple cases of std::cin usage
about the simplest cases of std::cin usage in C++.

Dynamically memory allocation

It is code to reverse the values as they entered.When I am running the following code. It is taking 8 inputs only. After that it is not printing anything.
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int *p = new int(sizeof(int)*n);
int q = n;
for(int i=0;i<n;i++)
{
cin>>*p;
p++;
}
for(int j=0;j<n;j++)
{
cout<<*p<<" ";
p--;
}
return 0;
}
You can also try the following answer.
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int *p = (int *)malloc(sizeof(int)*n);
int q = n;
for(int i=0;i<n;i++)
{
cin>>*p;
p++;
}
for(int j=0;j<n;j++)
{
p--;
cout<<*p<<" ";
}
free(p);
return 0;
}
#include <iostream>
using namespace std;
(Not related to the title, but using namespace std is bad practice that can lead to breakage when switching compilers, for example. Better write the std:: prefix when needed, such as std::cin >>.
int main() {
int n;
cin>>n;
int *p = new int(sizeof(int)*n);
The above is allocating a single int object, whose value is sizeof(int)*n, and p points to that integer. You probably mean:
int *p = (int*)malloc(sizeof(int)*n); // bad style
... at the end:
free(p);
But using malloc in C++ is a bad idea, unless you want to go closer to the operating system for educational purposes.
Slightly better is to use new, which besides allocating the objects also calls their constructors (but nothing is constructed for basic types such as int).
int *p = new int[n]; // so-so style
... at the end:
delete [] p;
The above is not the best practice because it requires manual memory management. Instead, it is recommended to use smart pointers or containers whenever possible:
std::vector<int> p(n);
// continue with the code, just like with the pointers
Or allocate the individual elements only when needed.
std::vector<int> p;
p.reserve(n); // this is a minor optimization in this case
// ...
if (int value; std::cin >> value)
// This is how to add elements:
p.push_back(value);
else
std::cin.clear();
This looks ok:
int q = n;
for(int i=0;i<n;i++)
{
cin>>*p;
p++;
}
But this is broken. When the loop starts, p points after the last element. The following *p dereferences a pointer which goes past the last element:
for(int j=0;j<n;j++)
{
cout<<*p<<" ";
p--;
}
Replacing the order of pointer decrement and dereference avoids the crash:
for(int j=0;j<n;j++)
{
p--;
std::cout << *p << " ";
}
Ok, there many issues here:
int *p = new int(sizeof(int)*n);
This memory allocation is wrong. It allocates n times sizeof(int) bytes, so if int is 4 bytes long it will allocates n * 4 integers.
int q = n;
q variable is never used.
for(int i=0;i<n;i++)
{
cin>>*p;
p++;
}
There is no need for pointer arithmetic here. It would be better to access the array in simple p[i] way.
for(int j=0;j<n;j++)
{
cout<<*p<<" ";
p--;
}
Same here...
return 0;
}
You allocated memory, but never deallocate. This will cause memory leaks.
A better, correct version of the program could be:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int * p = new int[n];
for (int i = 0; i < n; ++i)
{
cin >> p[i];
}
for (int i = (n - 1); i >= 0; --i)
{
cout << p[i] << ' ';
}
delete [] p;
return 0;
}

Array of Nodes: Initialization

#include <iostream>
#include <vector>
#include <string>
#include <math.h>
using namespace std;
struct Node{
string data;
Node* next;
Node(){
data = "";
next = NULL;
}
};
int computeHash(string s, int m){
int p = 1000000007;
int x = 263;
unsigned long long sum = 0;
unsigned long long val = 0;
for(int i = 0; i < s.length(); i++){
val = pow(x, i);
sum = (sum + s[i] * val) % p;
}
sum = sum % m;
return sum;
}
int main(){
int buckets;
cin >> buckets;
int n;
cin >> n;
string tag;
string s;
vector< vector<string> > myStore(n);
for(int i = 0; i < n; i++){
cin >> s;
myStore.at(i).push_back(s);
cin >> tag;
myStore.at(i).push_back(tag);
}
Node** arr= new Node*[buckets];
for(int i = 0; i < n; i++){
if(!myStore[i][0].compare("add")){
s = myStore[i][1];
int hash = computeHash(s,buckets);
cout << hash << endl;
}
}
return 0;
}
I am trying to write a program to implement hashing with chains. I am trying to create an array of nodes so that I can append if two strings have the same hash value.
But I am having a problem with the initialization of array of Nodes. I thought the nodes in the array would be pointing to NULL. But when I tried to debug in gdb it is showing some other thing.
Can someone explain where I am wrong on comment about this behavior. Why arr1 and arr[2] are pointing to some memory location instead of null. I also tried to remove the default constructor but still getting the same results. Any help would be appreciated.
You're allocating an array of pointers. Pointers don't have constructors, or default initialization; you're getting random memory (from the allocation).
If you want the array to be NULL-ed out, you need to do so yourself (eg: memcpy, etc.).
You have initialized vector of size n of vectors of size 0 of strings.
Then you want to get the '[1]' (the second element of empty vector of strings)
You have to inutialize them separately.
e.g. in "for" cycle.
Updated. Use myStore.at(i).at(1) instead of myStore[i][1] to achieve checking of boundary conditions. (Try it, you will understand that the problem with vector indeed)

One of the values in a dynamically allocated array always prints a garbage value

Why is p[1].x printing out to a garbage value?
Is it possible to initialize a dynamically allocated array to a given array? If yes, then how?
#include <ioStream>
using namespace std;
struct point{
int x;
int y;
};
int N;
point *p = new point[N];
int main(){
cin>>N;
for(int i=0; i<N; i++){
cin>>p[i].x>>p[i].y;
}
for(int i=0; i<N; i++){
cout<<"("<<p[i].x<<", "<<p[i].y<<")"<<endl;
}
}
On these two lines, you are sizing an array with a variable that is zero initialized (N).
int N;
point *p = new point[N];
Therefore, you would be newing an array of length 0. This would lead to problems once you cin>>N because you use that variable to loop and write to the array, which will be writing outside the allocated space.
These types of cases really beg for std::array or std::vector.
Your code has undefined behaviour because variable N was not initialized with the number of potential elements of the array when it was used to allocate the array in the heap
int N;
point *p = new point[N];
That is as a global variable with the static storage duration it was assigned 0 by the compiler. According to the C++ Standard
When the value of the expression is zero, the allocation function is
called to allocate an array with no elements.
Rewrite your code at least like
#include <ioStream>
using namespace std;
struct point{
int x;
int y;
};
int main(){
int N;
cin>>N;
point *p = new point[N];
for(int i=0; i<N; i++){
cin>>p[i].x>>p[i].y;
}
for(int i=0; i<N; i++){
cout<<"("<<p[i].x<<", "<<p[i].y<<")"<<endl;
}
}
If you know the maximum number of points, better do something like:
const int MAXN = 1000;
Point p[MAXN];
int N;
cin >> N;
// ...
You can manually allocate space as well but you should read N first.
cin >> N;
Point *p = new Point[N];
// ...
A third option is to use a container (vector for dynamic arrays).
vector<Point> p;
cin >> N;
while(N--)
{ int x, y;
cin >> x >> y;
Point p_(x, y); // Assumes constructor exists
p.push_back(p_);
}