For my homework it is given one dimensional array and i have to convert it in a two dimensional array. The two dimensional array has 2 for the number of columns, because i have to represent the one dimensional array as pairs(the value of the number, the number of appearences in the array).
This is what have tried. The error appears on the last 2 lines of code: access violation writing location 0xfdfdfdfd.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
const int NR=17;
int arr[NR]={6,7,3,1,3,2,4,4,7,5,1,1,5,6,6,4,5};
int **newArr;
int count=0;
int countLines=0;
int searched;
for(int i=0;i<NR;i++)
{
newArr=new int*[countLines];
for(int i=0;i<countLines;i++)
{
newArr[i]=new int[2];
}
searched=arr[i];
if(i>0)
{
for(int k=0;k<countLines;k++)
{
if(newArr[countLines][0] == searched)
{
searched=arr[i]++;
}
for(int j=0;j<NR;j++)
{
if(searched==arr[j])
{
count++;
}
}
countLines++;
}
}
else
{
for(int j=0;j<NR;j++)
{
if(searched==arr[j])
{
count++;
}
}
countLines++;
}
newArr[countLines][0]=searched;
newArr[countLines][1]=count;
}
}
First you are using newArr in the first loop before allocating it any memory. You cannot dereference a pointer which owns no legal memory. It results in undefined behavior.
Secondly in the last part, you are allocating newArr a memory equal to countLines thus.
newArr = new int*[countLines] ;
It means that the indices in the first dimension of newArr are 0------>countLines-1. Doing newArr[countLines][0] = searched ; is again undefined. Make it newArr[countLines - 1].
I'm not going to bother with a line-by-line code analysis since (a) you're changing it while people are answering your question and (b) it would literally take too long. But here's a summary (non-exhaustive) of klunkers:
You are leaking memory (newArr) on each loop iteration starting with the second.
You're out-of-bounds on your array access multiple times.
You should not need to use a pointer array at all to solve this. A single array of dimension [N][2] where N is the number of unique values.
One (of countless many) way you can solve this problem is presented below:
#include <iostream>
#include <algorithm>
int main()
{
// 0. Declare array and length
int arr[]={6,7,3,1,3,2,4,4,7,5,1,1,5,6,6,4,5};
const size_t NR = sizeof(arr)/sizeof(arr[0]);
// 1. sort the input array
std::sort(arr, arr+NR);
/* alternaive sort. for this input size bubble-sort is
more than adequate, in case your limited to not being
allowed to use the standard library sort */
/*
for (size_t i=0;i<NR;++i)
for (size_t j=i+1;j<NR;++j)
if (arr[i] > arr[j])
{
arr[i] ^= arr[j];
arr[j] ^= arr[i];
arr[i] ^= arr[j];
}
*/
// 2. single scan to determine distinct values
size_t unique = 1;
for (size_t i=1;i<NR;++i)
if (arr[i] != arr[i-1])
unique++;
// 3. Allocate a [unique][2] array
int (*newArr)[2] = new int[unique][2];
// 4. Walk array once more, accumulating counts
size_t j=0;
newArr[j][0] = arr[0];
newArr[j][1] = 1;
for (size_t i=1;i<NR;++i)
{
if (arr[i] != arr[i-1])
{
newArr[++j][0] = arr[i];
newArr[j][1] = 0;
}
++newArr[j][1];
}
// 5. Dump output
for (size_t i=0;i<unique;++i)
cout << newArr[i][0] << " : " << newArr[i][1] << endl;
delete [] newArr;
return EXIT_SUCCESS;
}
Output
1 : 3
2 : 1
3 : 2
4 : 3
5 : 3
6 : 3
7 : 2
Related
Number can't be in array if it can be divided by number of elements of array (for example: in array which has 10 elements, numbers 1,2,5 and 10 are not "welcome"). So I need to find all these elements in array and kick them out. After that length of array changes, and then some other elements can be "not welcome" in array. I have to repeat it until array is without these elements. In the end, I have to calculate remaining elements and print them out. (I'm using C++)
I didn't know how to delete element from array, and just set value to 0.
I get input n (number of elements in array) and then all of these elements.
So, I already tried it but I'm sure there is much more effective way to do it :P Here is the code:
int main()
{
short int b = 0;
short int n;
int result = 0;
cin >> n;
int m = n;
int numbers[n];
for (int i = 0; i < n; i++) {
cin >> numbers[i];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j<=n; j++) {
if(numbers[j] != 0) {
if(n % numbers[j] == 0) {
numbers[j] = 0;
b = b + 1;
} }
}
n = n - b;
b = 0;
}
for (int i = 0; i < m; i++) {
result += numbers[i];
}
cout << result;
return 0;
}
example input: 10 1 2 3 4 5 6 7 8 9 10
example output: 24
I didn't know how to delete element from array
It is not possible to "delete element from array". An array of n elements begins its life with n elements, has n elements throughout its entire lifetime, and ends its life with n elements. It is not possible to change the size of an array.
Another problem:
cin >> n;
int numbers[n];
The size of an array must be a compile time constant. n is not a compile time constant. This is not a well-formed C++ program.
An array of runtime size must be allocated dynamically. The easiest solution is to use std::vector. The size of a vector can change, and you can use std::vector::erase to remove elements from it.
I'm using dynamic 2D array and need the value of particular index but it is not printing the correct value.
```int u=5;//No. of elements
int S[u];
int i=0;
while(i<u)//elements in universal set
{
cin>>S[i];
i++;
}
int n;
cin>>n;//no. of subset
i=0;
int subcost[n];
int **subset;
subset=new int*[n];
while(i<n)
{
int l,c;
cin>>l;//size of ith subset
subset[i]=new int[l];
int j=0;
while(j<l)//Elements in each subset
{
cin>>subset[i][j];
j++;
}
cin>>c;//cost for each subset
subcost[i]=c;
i++;
}
i=0;
while(i<n)
{
int j=0;
int s=*subset[i];
while(j<s)
{
cout<<subset[i][j]<<"\n";
j++;
}
i++;
}```
I expect the output to be value of each subset, but the actual output is totally different.
arr[i]=new int[n1];
There's a misunderstanding of what new does. (Perhaps you come from Java?) This doesn't store an integer with the value of n1. It instead creates an array with a size of n1.
Just one pointer level should be enough for an array:
int n = 5;
int i = 0;
int *arr;
arr = new int[n];
arr[i] = 100;
cout << arr[i] << endl; // output: 100
delete[] arr; // remember to deallocate – otherwise memory leaks will haunt your system!
If you're looking for a 2D array, a pointer to a pointer (**) will work.
int **arr;
arr = new int[n]; //
arr[0] = new int[n]; // allocate first array
arr[0][0] = 100; // set first element of first array
delete[] arr[0];
delete[] arr; // deallocate
Here
arr[i]=new int[n1]; /* allocating memory for arr[i], equal to n1*sizeof(int) bytes & arr[i] gets points to address returned by new */
cout<<"Value of "<<i<<"th row is :- "<<arr[i]<<"\n";
I expect the output to be value of n1, but the actual output is some
random address ?
yes, arr[i] is dynamically created array & printing it will prints its base address only.
Try this version where I tried to explain code changes in comments.
int main(void) {
std::cout<<"Enter the value of n"<<"\n";
int n;
std::cin>>n;
int **arr;
/* allocate memory for arr. arr holds base address of array of n int ptr */
arr=new int*[n];
int i=0;
int n1;
std::cout<<"Enter the value of n1"<<"\n";
std::cin>>n1;
/* allocate memory for arr[0], arr[1] .. */
while(i < n1) {
arr[i]=new int[n1];
i++;
}
/* put the data into dynamically allocated array */
for(int row = 0; row < n; row++) {
for(int col = 0; col < n1; col++) {
std::cin>>arr[row][col];
}
}
/* printh te data */
for(int row = 0; row < n; row++) {
for(int col = 0; col < n1; col++) {
std::cout<<"Value of "<<i<<"th row is :- "<<arr[row][col];
}
std::cout<<"\n";
}
return 0;
}
And since you created dynamic array using new you need to free the dynamically allocated memory to avoid memory leakage, use delete operator accordingly.
As pointed by others std::vector is better option than above one.
While you have a good answer from #Achal for dynamically allocating, as mentioned, you really should use the container vector provided by C++ to make things much easier and more robust. All C++ containers provided automatic memory management freeing you from having to allocate manually (and with much less chance of getting it wrong)
When using containers, such as a vector of vectors to store your data, you can simply read and discard your "//elements in universal set", "//no. of subset" and "//Elements in each subset". Those values are not required when using containers. You simply read the value you want and add it to your container, the container will grow as needed to accommodate.
While it is not 100% clear what your input data looks like, we can deduce from your file it looks something like:
Example Input File
Where your first integers is your "//elements in universal set" which isn't needed to read the data. Likewise the second line, your "//no. of subset" is irrelevant for reading the data. Finally the 1st element on each data row, your "//Elements in each subset" is also not needed. Each of these values is simply read and discarded to arrive at your final data set.
$ cat dat/universal_sub.txt
5
4
5 1 2 3 4 5
3 1 2 3
4 1 2 3 4
6 1 2 3 4 5 6
The Final Dataset You Want To Store
From the full file, these appear to be the actual data values you want to store (there can be an even number, but there is no requirement for that)
1 2 3 4 5
1 2 3
1 2 3 4
1 2 3 4 5 6
There are many different ways you can put the pieces together. A short example of how to get your final dataset from your input file could be:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <limits>
int main (void) {
std::string line; /* string for reading each line */
std::vector<std::vector <int>> subset; /* vector<vector<int>> */
int universal, nsubsets; /* two int to read/discard */
if (!(std::cin >> universal >> nsubsets)) { /* read/dicard 2 values */
std::cerr << "error: failed to read universal.\n";
return 1;
}
/* read/discard '\n' (any chars) left in input buffer line by cin above */
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
while (getline (std::cin, line)) { /* read each remaining data line */
int unneeded, i; /* 1st value and i for rest */
std::vector<int> tmp; /* vector<int> for each line */
std::stringstream ss (line); /* stringstream to read from */
if (ss >> unneeded) { /* read/discard 1st value */
while (ss >> i) /* read rest from stringstream */
tmp.push_back(i); /* add to tmp vector */
subset.push_back(tmp); /* add tmp vector to subset */
}
}
for (auto& i : subset) { /* loop over subsets */
for (auto& j : i) /* loop over each value in subset */
std::cout << " " << j; /* output value */
std::cout << '\n'; /* tidy up with newline */
}
}
(note: the output loops make use of the Range-based for loop (since C++11) but you are free to use the .begin() and .end() container functions with a traditional for loop if your compile does not support std=c++11)
Exaple Use/Output
Reading your data into a vector of vectors allows accessing each element:
$ ./bin/vector_2d_subset < dat/universal_sub.txt
1 2 3 4 5
1 2 3
1 2 3 4
1 2 3 4 5 6
Look things over and let me know if you have further questions or if I interpreted your data file format incorrectly.
So I was asked to write a program which uses a pointer that points to the first element in an array and pass the pointer to a function. Then using only pointer variables (and looping constructs), print only the array values that are exact multiples of 7. Here's the script:
#include <iostream>
using namespace std;
void print_sevens(int *nums,int length){
for(int i = 0; i < length; i++){
nums = nums + i;
if(*nums % 7 == 0)
cout << *nums << endl;
}
}
int main() {
int a[5]={7,49,2,8,70};
int *p1 = &a[0];
print_sevens(p1,5);
}
The output from this is :
7
49
-149462114
I can't find out what is wrong. Any help is appreciated. Thanks
nums is the pointer to the start of the array. You are reassigning it at every loop iteration to be nums + i, not nums + 1. So, at the fourth iteration, for example, nums points to the initial array start + 0 + 1 + 2 + 3, which is the seventh element in your array of 5 elements. That's why you get garbage.
Use a subscript to make your life easy:
for(int i = 0; i < length; i++){
if(nums[i] % 7 == 0)
cout << nums[i] << endl;
}
I was trying to solve the following problem,
Given an array of integers, every element appears three times except
for one. Find that single one.
When the input are all positive, I will not get any errors, but when the input contains negative integers, the line delete index; will give error, does anybody know why?
i.e.
A[] = {1,2,3,4,1,2,3,4,1,3,4} works fine, but A[] = {-2,-2,1,1,-3,1,-3,-3,-4,-2} does not.
The code is as follow,
#include <iostream>
#include <map>
class Solution {
public:
int singleNumber(int A[], int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int *index;
std::map<int, int> m;
index = new signed int[(n+1)/3];
int flag = 0;
int result;
for(int i=0; i<n; i++) {
if(m.find(A[i]) == m.end()) {
m[A[i]] = 1;
index[flag] = A[i];
flag++;
} else {
m[A[i]] = m[A[i]] + 1;
}
}
for(int i=0; i<(n+1)/3; i++) {
if(m[index[i]] != 3) {
result = index[i];
}
}
delete index;
return result;
}
};
int main()
{
Solution s;
int A[] = {1,2,3,4,1,2,3,4,1,3,4};
int result = s.singleNumber(A, 11);
std::cout <<result;
return 0;
}
The first array contains 11 elements, which causes the line index = new signed int[(n+1)/3]; to allocate an array of (11+1)/3 = 4 elements. The second array contains 10 elements, which causes that line to allocate an array of (10+1)/3 = 3 elements.
3 elements is insufficient to record the unique values in A (-4, -3, -2, and 1), so you overflow the array.
You should allocate at least (n+2)/3 elements. It would also be prudent to test the value of flag to ensure it never exceeds the array bounds. It will not if the input array obeys the constraint that every element but one appears three times (presuming this means it will appear one or two times, not four or more), but can you rely on that constraint being obeyed?
Additionally, the loop for(int i=0; i<(n+2)/3; i++) is insufficient to iterate through all the elements that were added to the map. You should be sure you iterate through all the members of m.
Incidentally, singleNumber can be implemented in a much more fun way without any dynamic allocation or library calls:
int singleNumber(int A[], int n) {
int b = 0, c = 0;
while (n--)
{
b ^= A[n] & c;
c ^= A[n] & ~b;
}
return c;
}
However, this is completely not what your instructor is expecting.
I got an assignment to reverse an dynamic array in C++. So far, from my logic, I thinking of loop thru the array to reverse it. And here comes my code :
int main ()
{
const int size = 10;
int num_array[size];
srand (time(NULL));
for (int count = 0; count< sizeof(num_array)/sizeof(num_array[0]) ; count++){
/* generate secret number between 1 and 100: */
num_array[count] = rand() % 100 + 1;
cout << num_array[count] << " " ;
}
reverse(num_array[size],size);
cout << endl;
system("PAUSE");
return 0;
}
void reverse(int num_array[], int size)
{
for (int count =0; count< sizeof(num_array)/sizeof(num_array[0]); count++){
cout << num_array[sizeof(num_array)/sizeof(num_array[0])-1-count] << " " ;
}
return;
}
Somehow I think my logic was there but this code doesn't works, there's some error. However, my teacher told me that this isn't the way what the question wants. And here is the question :
Write a function reverse that reverses the sequence of elements in an array. For example, if reverse is called with an array containing 1 4 9 16 9 7 4 9 11,
then the array is changed to 11 9 4 7 9 16 9 4 1.
So far, she told us in the reverse method, you need to swap for the array element. So here's my question how to swap array element so that the array entered would be reversed?
Thanks in advance.
Updated portion
int main ()
{
const int size = 10;
int num_array[size];
srand (time(NULL));
for (int count = 0; count< size ; count++){
/* generate secret number between 1 and 100: */
num_array[count] = rand() % 100 + 1;
cout << num_array[count] << " " ;
}
reverse(num_array,size);
cout << endl;
system("PAUSE");
return 0;
}
void reverse(int num_array[], const int& size)
{
for (int count =0; count< size/2; count++){
int first = num_array[0];
int last = num_array[count-1];
int temp = first;
first = last;
last = temp;
}
}
You reverse function should look like this:
void reverse(int* array, const size_t size)
{
for (size_t i = 0; i < size / 2; i++)
{
// Do stuff...
}
}
And call it like:
reverse(num_array, size);
I am no C++ programmer, however I do see an easy solution to this problem. By simply using a for loop and an extra array (of the same size) you should be able to reverse the array with ease.
By using a for loop, starting at the last element of the array, and adding them in sequence to the new array, it should be fairly simple to end up with a reversed array. It would be something like this:
Declare two arrays of the same size (10 it seems)
Array1 contains your random numbers
Array2 is empty, but can consist of 10 elements
Also declare an integer, which will keep track of the progression of the for loop, but in the opposite direction. i.e not from the end but from the start.
Counter = 0
Next you will need to create a for loop to start from the end of the first array, and add the values to the start of the second array. Thus we will create a for loop to do so. The for loop will be something like this:
for(int i = lengthOfArray1; i > 0; i--){
Array2[Counter] = Array1[i]
Counter++
}
If you only wish to print it out, you would not need the counter, or the second array, you will simply use the Array1 elements and print them out with that style of for loop.
That's it. You could set Array1 = Array2 afterward if you wished to keep Array1 the original for some reason. Hope this helps a bit, changing it to C++ is your job on this one unfortunately.
You're not actually swapping the elements in the array, you're just printing them out. I assume she wants you to actually change what is stored in the array.
As a hint, go through the array swapping the first and last element, then the 2nd and 2nd last element, etc. You only need to loop for size/2 too. As you have the size variable, just use that instead of all the sizeof stuff you're doing.
I would implement the function like following
void reverse(int A[], int N)
{
for (int i=0, j=N-1; i<j; i++, j--){
int t = A[i];
A[i] = A[j];
A[j] = t;
}
}