How to compare two 2d arrays of char in C/ C++ [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am passing two 2d arrays of char into a function, that will return 1 if the arrays are equal and 0 otherwise.
size of the arrays is [4][4], However when I try to iterate through the array I get an error.
int checkIfWin(char** array, char** array2){
int winner = 0;
for(int i = 0; i < 4; i++){
if(strcmp(array2[i], array[i])==0){
winner = 1;
}
else
winner = 0;
}
return winner;
}
UPDATE:
The reason why I was getting an errorn while strcmp is because I did not malloc the second 2d array.

char[] is different from char *, the first places the value '\0' at the end of the array instead the second does not.
The function strcmp will compare the elements until it finds the value '\0', for that task better compare element to element and if you find a difference returns automatically.
int checkIfWin(char** array, char** array2){
for(int i = 0; i < 4; ++i){
for (int j = 0; j < 4; ++j){
if(array2[i][j] != array[i][j]){
return 0;
}
}
}
return 1;
}

Here is a solution using strncmp():
int winner = 1, i;
for(i = 0; i < 4; i++){
if((strncmp(array2[i], array[i], 4)) != 0){
winner = 0;
break;
}
}
return winner;

Related

Is this the correct implementation of Insertion Sort? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
OUTPUT
#include <iostream>
using namespace std;
int main()
{
//declaring the size of array and taking input from the user
int n = 0;
cout<<"Enter the Number of elements you want in the Array : ";
cin>>n;
//checking the user input
if(n <= 0)
{
cout<<"Not Possible\n";
return 1;
}
//declaring array of size 'n' and taking input from user
int list[n];
cout<<"Enter the Elements of the array of size "<<n<<" : ";
for(int i = 0; i < n; i++)
cin>>list[i];
//Insertion Sort
int swap = 0; //number of swaps
int comp = 0; //number of comparison
int temp; //temporary variable
for(int i = 0; i < n-1; i++)
{
for(int j = i+1; j > 0; j--)
{
if(list[j] < list[j-1])
{
//swapping equivalent to shifting
temp = list[j-1];
list[j-1] = list[j];
list[j] = temp;
comp++;
swap++;
}
else
{
comp++;
break;
}
}
//printing the iteration
cout<<"Iteration "<<(i+1)<<" : ";
for(int k = 0; k < n; k++)
cout<<list[k]<<" ";
cout<<"\n";
}
cout<<"\nSwap : "<<swap<<"\n";
cout<<"Comparison : "<<comp<<"\n";
cout<<"Sorted Array : ";
for (int i = 0; i < n; i++)
{
cout<<list[i]<<" ";
}
return 0;
}
Is this implementation of insertion sort correct because I have seen many implementation online using while loop and other things?
If not can you point out what is wrong?
Thanks in advance
link - https://github.com/ish-u/DiscreteStructures/blob/master/InsertionSort.cpp
No, this is a different type of sort, known as bubble sort. It still sorts, but insertion sort works in a different way, by keeping the array sorted at all times (moving elements if a new insertion would break the ordering).
So instead of just tagging new elements to the end of the array where you read them from cin, you should place each element directly in the right spot in the array. This will likely involve moving existing elements in order to keep the array sorted.
Note that your line
int list [n];
is wrong; you cannot allocate memory this way (and I'm surprised it even compiles). A better choice would be to use std::vector.

How to convert a 2D array into a single string in c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Am writing a pathfinder and have a 21x21 array which I want to convert into a single string. The array will contain only 1's and 0's. The 1's are placed together in order to form the path.
My current relevant code snippet is
std::string str;
for(int i = 0; i < 21; i++)
{
for(int j = 0; j < 21; j++)
{
str += grid[i][j];
}
}
std::cout << str;
return (str);
When I run the code it jumps to a file containing
static inline size_t length(const char_type* __s) {return strlen(__s);} and says EXC_BAD_ACCESS.
Just use this code in your loop
str +=std::to_string(grid[i][j]);
It seems like you are attempting to access index 20 which isn't available, because you have started the loop from 0.
You can change the iteration limits from 0 to 20.
Your array is 20x20, so from index 0 to 19.
Your for loops are checking from index 0 to 20.
index [20] doesn't exist.
Change "i < 21" in your for loop to : i < 20. Same for J.
grid[i][0] is acting a char pointer that has only been allocated 20 bytes of space, so the += operation is protecting you from grabbing garbage data that lies beyond that last byte.
You are iterating too far in you grid. your loops should be:
std::string str;
// iterate through i index from 0 to 19.
for(int i = 0 ; i < 20; i++)
{
// iterate through j index from 0 to 19.
for(int j = 0 ; j < 20 ; j++)
{
// After testing it you do need to replace str += a[i][j]; for it to do what you want.
str.append(std::to_string(grid[i][j]));
}
}
std::cout << str;
return(str);
After your correction about how grid was initialized I wrote a test to see if I could get your issue I could not. However without the append(to_string) change it would not produce the string you would expect. It interprets the int as a char and puts a character who's ASCII numeric value is 0 or 1. instead of using the '0' or '1' characters who's numeric ASCII code values are 48 and 49.
This was my complete test program: compiled with "g++ -std=c++11 " on a Ubuntu VM.
#include<iostream>
int main()
{
int a[21][21] = {};
a[1][1]=1;
a[2][1]=1;
std::string str;
for (int i = 0 ; i < 21; ++i)
{
for (int j = 0; j < 21; ++j)
{
str.append(std::to_string(a[i][j]));
}
}
std::cout << str << std::endl;
}
The output:
000000000000000000000010000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Segmentation Fault in g++ and reading from files [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a problem with this program, it reads from two files.
Each file, A and B contains an int at the top wich is the number of the strings it has. The program has to do a B - A operation, file A has 2 strings, "two" and "three". File B has 4 strings, "one", "two", "three" and "four". So the result in the third file has to be "one" and "four". Those which are not in the file A, but yes in file B.
First I read the size of each file, then the strings of each one.
I calculate the size of result file and compare the strings of the two files.
I have used gdb debugger and it says that the problem is in the for that compares the files. What I do is:
If string in B, is not found in A, I put it in the result.
I write here the whole program (not too big) so you can get a better idea.
Many thanks and sorry for spanish name in variables.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main(){
int contador = 0;
string* datosA;
string* datosB;
string* resultado;
int tamA, tamB, tamResultado;
ifstream fichA("fA.txt");
if(fichA){
fichA>> tamA;
datosA = new string [tamA];
for(int i = 0; i < tamA; i++){
fichA>> datosA[i];
}
fichA.close();
}
ifstream fichB("fB.txt");
if(fichB){
fichB>> tamB;
datosB = new string [tamB];
for(int i = 0; i < tamB; i++){
fichB>> datosB[i];
}
fichB.close();
}
tamResultado = tamB - tamA;
resultado = new string [tamResultado];
contador = 0;
for(int i = 0; i < tamB; i++){
bool enc = true;
for(int j = 0; j < tamA && enc; j++){
if(datosB[i] != datosA[j]){
enc = false;
}
}
if(!enc){
resultado[contador] = datosB[i];
contador++;
}
}
delete[] datosA;
delete[] datosB;
ofstream fout("resultado.txt");
if(fout){
for(int i = 0; i < tamResultado; i++){
fout<< resultado[i];
}
fout.close();
}
delete[] resultado;
datosA = datosB = resultado = 0;
return 0;
}
Check your conditions.
You are changing your flag whenever you come across different element. But it should happen only when ALL of the elements in the array A are different from the one in the array B for specific position.
The way it is written now, you are trying to add all four elements from array B to your resulting array which is segmentation fault because you are trying to access unallocated memory.
One possible solution would be to add counter which checks if both elements in array A are different from the element in array B.
Something like this:
for(int i = 0; i < tamB; i++){
bool enc = true;
// counter that keeps track of number of different elements
int count = 0;
for(int j = 0; j < tamA && enc; j++){
if(datosB[i] != datosA[j]){
count++;
}
}
// check if all elements in datosA are different than datosB[i]
if(count == tamA){
resultado[contador] = datosB[i];
contador++;
} }
That should work as intended.

Removing more than one element from an array and creating a dynamic array c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm still new to c++ so this is a learning process for me. Also i know that i should initially use a vector to do this but i have an exercise that specifies an array so i'm trying to write a function that removes all duplicate elements in an array but i receive the error
C2100: illegal indirection
if someone could point me in the right direction
int main()
{
int *t;
int removel[9] = { 1, 1, 1, 2, 3, 4, 5, 6, 6, };
t = removeAll(removel, 9, 1);
for (int i = 0; i < 8; i++)
cout << t[i] << " ";
}
int* removeAll(int list[], int listlength, int removeitem)
{
int count = 0;
int* list2;
int removeindex;
int length;
int tempindex;
for (int i = 0; i < listlength; i++)
{
if (removeitem == list[i])
count++;
}
length = listlength - (count + 1);
list2 = new int[length];
int j;
while (j<=length)
{
remove_if(list[0], list[listlength - 1], removeitem);
for (j = 0; j < length; j++)
if (list[j] == NULL)// not sure what the remove_if func puts inplace of the removed element
continue;
else
list2[j] = list[j];
}
return list2;
}
Firstable you should calculate length like listlength - count, not listlength - (count + 1).
Then, after list2 = new int[length]; you should copy elements which are different with removeitem and skip other ones. You can do it like this
int j = 0;
for (int i = 0; i < listlength; i++) {
if (removeitem == list[i])
continue;
list2[j] = list[i];
j++;
}
and return successfully created list2. But you should also know its size. You can do it by creating int tSize in main and pass it to removeAll by link. removeAll will change its value to length. So add int & list2size to the parameters list of removeAll and write list2size = length; before returning list2. Finally, when printing t, change i < 8 to i < tSize.
If you do all this program will work right but don't forget about formatting.

C++ For Loop: invalid operands to binary expression [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to copy data from one vector to another but am getting an error , "Invalid operands to binary expression 'int' and 'Card' " when I try to compile the following for loop:
for (int i = 0; i <= vectorOne[vecCapacity]; i++) { //step 3
vectorTwo[i] = vectorOne[i];
}
Would anyone have any suggestions?
I believe what you meant is
for (int i = 0; i <= vecCapacity; i++)
or even more likely
for (int i = 0; i < vecCapacity; i++)
The error message is clear enough: in this loop
for (int i = 0; i <= vectorOne[vecCapacity]; i++) { //step 3
vectorTwo[i] = vectorOne[i];
}
i has type int while vectorOne[vecCapacity] has type Card and there is no defined operator <= for these types.
So this loop makes no sense.
Maybe you mean
for (int i = 0; i < vecCapacity; i++) { //step 3
vectorTwo[i] = vectorOne[i];
}
Also take into account that you have to guarantee that the size of vectorTwo is not less than the size of vectorOne or at least vecCapacity.
You could use standard algorithm std::copy declared in header <algorithm>
For example
#include <algorithm>
//...
std::copy( vectorOne, vectorOne + vecCapacity, vectorTwo );
You should be looping from 0 to vectorOne's size.
for (int i = 0; i < vectorOne.size(); i++) { //step 3
vectorTwo[i] = vectorOne[i];
}`
`
Also, if you're doing it this way, make sure vectorTwo is big enough before the loop.
vectorTwo.resize(vectorOne.size());