Multiplying matrices using pointers - c++
Hey guys I am trying practice learning pointers in c++. So I am trying to multiply these arrays and am getting all 0's in my resulting matrix. if anybody could just hint to me what to look at or some advice on what is causing this that would be amazing.
Here is the code:
#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
#include <iostream>
/* Routines called. */
int loadMatrixFromFile(char *filename, int *data);
void showMatrix(int *data, int len);
int makeIdent(int matrixB[5][5], int length);
int matrixA[5][5];
int matrixB[5][5];
int matrixC[5][5];
void multiplyMatrices(int matrixA[5][5], int matrixB[5][5],int matrixC[5][5]);
int main(){
int len, data[1000];
len = loadMatrixFromFile("Numbers.txt", data);
showMatrix(data, len);
makeIdent(matrixB, len);
multiplyMatrices(matrixA, matrixB, matrixC);
}
int makeIdent(int matrixB[5][5], int len){
int i,j;
int *ptr;
ptr = &matrixB[5][5];
printf("Matrix B is: \n");
for(i=0;i<5;i++){
for(j=0;j<5;j++){
if(i==j){
*ptr=1;
printf("%d ", *ptr);
}
else{
*ptr=0;
printf("%d ",*ptr);
}
}
printf("\n");
}
return *ptr;
printf("\n");
}
int loadMatrixFromFile(char *filename, int *data){
FILE *in;
int len;
int j;
in = fopen(filename, "r");
if (in == NULL) {
printf("Could not find file: %s \n", filename);
}
else {
printf("Reading numbers...\n");
fscanf(in, "%d", &len);
printf("reading %d numbers from file %s ....\n", len, filename);
for(j=0;j<len;j++) {
fscanf(in, "%d", data + j);
}
fclose(in);
}
for(int i = 0; i<5; i++){
for(int j = 0; j < 5; j++){
matrixA[i][j] = *(data + i*5 + j);
}
}
return len;
}
void showMatrix(int *data, int len){
int j;
int count = 0;
printf("Showing %d numbers from data array....\n", len);
printf("Matrix A is: \n");
for(j=0;j<len;j++) {
printf("%d ", *(data + j));
count++;
if(count % 5 == 0){
printf("\n");
}
}
printf("\n");
}
void multiplyMatrices(int matrixA[5][5], int matrixB[5][5],int matrixC[5][5]){
int i, n, j;
int *ptr1, *ptr2, *ptr3;
ptr1 = &matrixA[5][5];
ptr2 = &matrixB[5][5];
ptr3 = &matrixC[5][5];
printf("\n");
printf("Matrix A x Matrix B is: \n");
for(i=0;i<5;i++){
for(j=0;j<5;j++){
*ptr3=0;
}
}
for (i = 0; i<5; i++){
for (j = 0; j<5; j++){
for(n=0;n<5;n++){
*ptr3 += (*ptr1**ptr2);
}
printf("%d ",*ptr3);
}
printf("\n");
}
}
In makeIdent you need to increment ptr after each element. To
initialize ptr you need to point it to the first element in the array, not the last element.
int makeIdent(int matrixB[5][5], int len){
int i,j;
int *ptr;
ptr = &matrixB[0][0]; // note the 0 instead of the 5
printf("Matrix B is: \n");
for(i=0;i<5;i++){
for(j=0;j<5;j++){
if(i==j){
*ptr=1;
printf("%d ", *ptr);
}
else{
*ptr=0;
printf("%d ",*ptr);
}
ptr++; // this is new
}
printf("\n");
}
return 0;
}
This is closer to what you want for multiplyMatrices:
void multiplyMatrices(int matrixA[5][5], int matrixB[5][5],int matrixC[5][5]){
int i, n, j;
int *ptr1, *ptr2, *ptr3;
ptr1 = &matrixA[0][0];
ptr2 = &matrixB[0][0];
ptr3 = &matrixC[0][0];
for (i = 0; i<5; i++) {
for (j = 0; j<5; j++) {
*ptr3 = (*ptr1 * *ptr2);
ptr1++; ptr2++; ptr3++;
}
}
}
You could say this instead:
*ptr3++ = *ptr1++ * *ptr2++;
But I don't want to confuse the issue.
Related
fopen() gives me malloc(): corrupted top size
I am trying to write the contents of an array, to a binary file, but it gives the following errors when I run the file. malloc(): corrupted top size Process finished with exit code 134 (interrupted by signal 6: SIGABRT) Here is my code #include <iostream> #include <time.h> #include <fstream> #include <iostream> using namespace std; #define ONE 1 #define TWO 2 #define THREE 3 #define FOUR 4 #define FIVE 5 #define SIX 6 #define SEVEN 7 int getArrayLength(); void initializeArray(int *array, int length); void printArray(int *array, int length); void menu(int *array, int length); void userChoice(int userInput, int *array, int length); void serialSearch(int *array, int length, int givenNumber); void quickSort(int *array, int start, int end); int partition(int *array, int start, int end); void substitute(int *firstElement, int *secondElement); int binarySearch(int *array, int start, int end, int userChoice); void arrayConcatenation(int *firstArray, int *secondArray, int *concatenatedArray, int length, int doubleLength); int main() { int arrayLength = getArrayLength(); int *randomNumbersArray = (int *) malloc(arrayLength * sizeof (int)); initializeArray(randomNumbersArray, arrayLength); printArray(randomNumbersArray, arrayLength); menu(randomNumbersArray, arrayLength); return 0; } int getArrayLength() { int size; cout<<"Please give the size of the array: "; cin>>size; return size; } void initializeArray(int *array, int length) { srand(time(nullptr)); for(int i = 0; i < length; i++) *(array + i) = 30 + rand() % 21; } void printArray(int *array, int length) { for(int i = 0; i < length; i++) cout<<*(array + i)<<" "; cout<<endl; } void menu(int *array, int length) { int userInput; cout<<" Array Functions"<<"\n"<<endl; do { cout<<"1. Serial Search"<<endl; cout<<"2. Array Classification"<<endl; cout<<"3. Binary Search (classifies the array automatically)"<<endl; cout<<"4. Concatenation of classified arrays"<<endl; cout<<"5. Print"<<endl; cout<<"6. Save and read array with binary file"<<endl; cout<<"7. Exit"<<"\n"<<endl; cout<<"Please enter your choice: "; cout<<endl; cin>>userInput; userChoice(userInput, array, length); } while (userInput != SEVEN); } void userChoice(int userInput, int *array, int length) { FILE *myFile; int mergedLength = 2 * length; int *secondArray = (int *) malloc(length * sizeof (int)); int *mergedArray = (int *) malloc(length * sizeof (int)); initializeArray(secondArray, length); initializeArray(mergedArray, mergedLength); switch(userInput) { case ONE: { int givenNumber; serialSearch(array, length, givenNumber); break; } case TWO: { quickSort(array, 0, length-ONE); cout<<"This is the sorted array."<<endl; printArray(array, length); break; } case THREE: { int choice, existence; cout<<"What number you want?"<<endl; cin>>choice; quickSort(array, 0, length-ONE); existence = binarySearch(array, 0, length-ONE, choice); if (existence == -ONE) cout<<"The chosen number is not in the array."<<endl; else cout<<"The number is at index "<<existence<<"."<<endl; break; } case FOUR: { quickSort(array, 0, length-ONE); quickSort(secondArray, 0, length-ONE); arrayConcatenation(array, secondArray, mergedArray, length, mergedLength); quickSort(mergedArray, 0, mergedLength - ONE); cout<<"This is the first array in order"<<endl; printArray(array, length); cout<<"This is the second array in order."<<endl; printArray(secondArray, length); cout<<"This is the merged array in order."<<endl; printArray(mergedArray, mergedLength); myFile = fopen("binarydata.dat", "wb"); if(myFile == NULL) { cout<<"Error in file opening."<<endl; exit(0); } fwrite(array, sizeof (int ), length, myFile); fclose(myFile); break; } } free(secondArray); free(mergedArray); } void serialSearch(int *array, int length, int givenNumber) { int flag = -ONE; cout<<"Please give the number that you want to find in the array: "; cin>>givenNumber; for(int i = 0; i < length; i++) { if(*(array + i) == givenNumber) { cout<<"The number was found at position: "<<i<<"\n"<<endl; flag = 0; break; } } if(flag == -1) cout<<"The number is not in the array."<<"\n"<<endl; } void quickSort(int *array, int start, int end) { if (start < end) { int driver = partition(array, start, end); quickSort(array, start, driver-ONE); quickSort(array, driver+ONE, end); } } int partition(int *array, int start, int end) { int key = *(array + end); int i = start - ONE; for(int j = start; j < end; j++) { if(*(array + j) <= key) { i++; substitute((array + i), (array + j)); } } substitute((array +i + ONE), (array + end)); return(i + ONE); } void substitute(int *firstElement, int *secondElement) { int temp = *firstElement; *firstElement = *secondElement; *secondElement = temp; } int binarySearch(int *array, int start, int end, int userChoice) { if(end >= start) { int middle = start + (end - start)/2; if(*(array + middle) == userChoice) return middle; if(*(array + middle) > userChoice) return binarySearch(array, start, middle-1, userChoice); return binarySearch(array, middle+1, end,userChoice); } return -1; } void arrayConcatenation(int *firstArray, int *secondArray, int *concatenatedArray, int length, int doubleLength) { for(int i = 0; i < length; i++) *(concatenatedArray + i) = *(firstArray + i); for(int i = 0; i < length; i++) *(concatenatedArray + i + length) = *(secondArray + i); } The problem is in the case FOUR of the switch case part of the code.
reference array in mergesort algorithm produces values that were not existent in the original array
My mergesort algorithm works correctly, i.e. it sorts the values from the input array. However the reference array that is there to controle whether the array is really sorted produces values that were not in the original array that should be sorted and because of that the compiler throws an error. What can I do to solve this problem? I have configured the program so that it sorts one specific array, it has 103 values, I tried to reduce the size but then the program runs successfully. This is the input array: [1919243808,365,372,383,394,404,413,170931,667182,540028976,741551154,774455913,774778478,778265971,840969273,892416309,942815278,1292503603,1667851881,1869182049,1919243808,35,20,20,50,50,52,53,54,54,55,55,58,63,64,64,65,388,401,65,71,73,73,74,75,75,77,289,290,290,292,300,303,308,308,308,267,312,312,314,314,315,323,323,325,330,332,333,338,339,347,347,361,221,372,383,394,404,331,331,413,2,741551154,892416309,875310137,808531502,540028976,778265971,1919243808,1667851881,1869182049,774778478,1292503603,774455913,667182,356,359,361,362,363,364,365,741684787] It is saved in the reference array at the beginning of the program. To controle whether the change occurs at this point I printed out the reference array, and it is still the same as the input array. Then the mergesort algorithm runs on the input array. It gives the output array: [2,20,20,35,50,50,52,53,54,54,55,55,58,63,64,64,65,65,71,73,73,74,75,75,77,221,267,289,290,290,292,300,303,308,308,308,312,312,314,314,315,323,323,325,330,331,331,332,333,338,339,347,347,356,359,361,361,362,363,364,365,365,372,372,383,383,388,394,394,401,404,404,413,413,170931,667182,667182,540028976,540028976,741551154,741551154,741684787,774455913,774455913,774778478,774778478,778265971,778265971,808531502,840969273,875310137,892416309,892416309,942815278,1292503603,1292503603,1667851881,1667851881,1869182049,1869182049,1919243808,1919243808,1919243808] I checked with a helping program whether the output array is sorted, and it is really sorted. #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/time.h> #include <iostream> int arraySortedCheck(int arr[], int n){ for (int i = 0; i < n; ++i){ //when an array is not in sorted order if(arr[n-1] < arr[n-2]) return 0; } //all elements are checked and //all are in sorted order return 1; } int main(int argc, char const *argv[]){ int arr[103]{2,20,20,35,50,50,52,53,54,54,55,55,58,63,64,64,65,65,71,73,73,74,75,75,77,221,267,289,290,290,292,300,303,308,308,308,312,312,314,314,315,323,323,325,330,331,331,332,333,338,339,347,347,356,359,361,361,362,363,364,365,365,372,372,383,383,388,394,394,401,404,404,413,413,170931,667182,667182,540028976,540028976,741551154,741551154,741684787,774455913,774455913,774778478,774778478,778265971,778265971,808531502,840969273,875310137,892416309,892416309,942815278,1292503603,1292503603,1667851881,1667851881,1869182049,1869182049,1919243808,1919243808,1919243808}; int n = sizeof(arr)/sizeof(arr[0]); if(arraySortedCheck(arr, n)){ printf("Array is in sorted order\n"); } else printf("Array is not in sorted order\n"); return 0; } Sortcheckoutput: Array is in sorted order In the verification-phase of my program, the reference array is sorted with a library function and then compared to the output array from the mergesort algorithm, however this sorted reference array has values that were not there before "sorted reference array" [2,20,20,35,50,50,52,53,54,54,55,55,58,63,64,64,65,65,71,73,73,74,75,75,77,221,267,289,290,290,292,300,303,308,308,308,312,312,314,314,315,323,323,325,330,331,331,332,333,338,339,347,347,356,359,361,361,362,363,364,365,365,372,372,383,383,388,394,394,401,404,404,413,413,170931,667182,667182,540028976,540028976,741551154,741551154,774455913,774455913,774778478,774778478,778265971,778265971,808531502,840969273,875310137,892416309,892416309,942815278,959515229,1292503603,1292503603,1667851881,1667851881,1869182049,1869182049,1919243808,1919243808,959527217] Values that are new are for example 959527217 or 959515229 And therefore the verification says that the array is not the sorted input array even tough it is This is the code: #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/time.h> #include <iostream> #include <algorithm> #include <cstdlib> #include <cstdio> #include <cmath> #include <ctime> #include <cstring> #include <omp.h> // Constants.h #if !defined(MYLIB_CONSTANTS_H) #define MYLIB_CONSTANTS_H 1 #endif //Takes a sorted list of size n and a value, puts the value in one of n+1 possible positions, //if value is same to an element of the list take the position before the first occurence of the same element binarysearchfindlowerrank(int *in,int n,int value,int projection){ int* array= in+projection; int L=0; int R=n; printf("\nLowerBinarysearchrankfinder: ["); for(int i=0;i<n; i++){ printf("%d,",array[i]); } printf("]\n"); while(R-L>1){ int middle = (R+L)/2; printf("L:%d,middle:%d,R:%d,value:%d\n",L,middle,R,value); if(array[middle]==value){ while(array[middle]==value&&middle>0){ middle=middle-1; } if(middle==0&&array[middle]>=value){ return 0; } else{ printf("L:%d,middle:%d,R:%d,result:%d,index:%d\n",L,middle,R,(middle+1),(middle+1+projection)); return middle+1; } } if(array[middle]<value){ L=middle; } if(array[middle]>value){ R=middle; } } printf("L:%d,R:%d,value:%d\n",L,R,value); if(n==1){ if(array[0]>=value){ return 0; } else return 1; } if(L==0&&array[L]>value){ printf("L:%d,R:%d,result:%d,index:%d\n",L,R,0,0+projection); return 0; } if(R==n && array[R-1]< value){ printf("!!L:%d,R:%d,result:%d,index:%d\n",L,R,n,n+projection); return n; } if(R==n&& array[R-1]>=value){ printf("L:%d,R:%d,result:%d,index:%d\n",L,R,R-1,(R-1+projection)); return R-1; } if(array[R]<value){ printf("L:%d,R:%d,result:%d,index:%d\n",L,R,R+1,(R+1+projection)); return R+1; } if(array[L]<value){ printf("L:%d,R:%d,result:%d,index:%d\n",L,R,R,(R+projection)); return R; } printf("L:%d,R:%d,result:%d,index:%d\n",L,R,L,(L+projection)); return L; } //Takes a sorted list of size n and a value, puts the value in one of n+1 possible positions, //if value is same to an element of the list take the position after the last occurence of the same element binarysearchfinduperrank(int *in,int n,int value, int projection){ int* array= in+projection; int L=0; int R=n; printf("\nUpperBinarysearchrankfinder ["); for(int i=0;i<n; i++){ printf("%d,",array[i]); } printf("]\n"); while(R-L>1){ int middle = (R+L)/2; printf("L:%d,middle:%d,R:%d,value:%d\n",L,middle,R,value); if(array[middle]==value){ while(array[middle]==value&&middle<n){ middle=middle+1; } printf("L:%d,R:%d,result:%d,index:%d\n",L,R,middle,middle+projection); return middle; } if(array[middle]<value){ L=middle; } if(array[middle]>value){ R=middle; } } printf("L:%d,R:%d,value:%d\n",L,R,value); if(n==1){ if(array[0]> value){ printf(" result:0\n,index:%d\n",0+projection); return 0; } else{ printf(" result:1,index:%d\n",1+projection); return 1; } } if(L==0&&array[L]>value){ printf("L:%d,R:%d,result:%d,index:%d\n",L,R,0,projection); return 0; } if(R==n && array[R-1]<= value){ printf("L:%d,R:%d,result:%d,index:%d\n",L,R,n,n+projection); return n; } if(R==n&& array[R-1]>value){ printf("L:%d,R:%d,result:%d,index:%d\n",L,R,R-1,((R-1)+projection)); return R-1; } if(array[R]<=value){ printf("L:%d,R:%d,result:%d,index:%d\n",L,R,R+1,(R+1+projection)); return R+1; } if(array[L]<=value){ printf("L:%d,R:%d,result:%d,index:%d\n",L,R,R,R+projection); return R; } printf("L:%d,R:%d,result:%d,index:%d\n",L,R,L,L+projection); return L; } /** * helper routine: check if array is sorted correctly */ bool isSorted(int ref[], int data[], const size_t size){ std::sort(ref, ref + size); for (size_t idx = 0; idx < size; ++idx){ if (ref[idx] != data[idx]) { printf("\nFalscher Index:%d\n",idx); return false; } } return true; } /** * sequential merge step (straight-forward implementation) */ void MsMergeSequential(int *out, int *in, long begin1, long end1, long begin2, long end2, long outBegin,int *data,int *tmp) { if(begin1==end2){ out[begin1]=in[begin1]; printf("\n[%d]\n",out[begin1]); } if(begin1==begin2||begin2==end2){ out[begin1+binarysearchfinduperrank(in,1,in[end2],begin1)]=in[end2]; out[begin1+binarysearchfindlowerrank(in,1,in[begin1],end2)]=in[begin1]; printf("\n[%d,%d]\n",out[begin1],out[end2]); printf("\nDATA:n["); for (size_t idx = 0; idx < 103; ++idx){ printf("%d,",data[idx]); } printf("]\n"); printf("\nTMP:["); for (size_t idx = 0; idx < 103; ++idx){ printf("%d,",tmp[idx]); } printf("]\n"); } else{ printf("begin:%d,middle1:%d:,middle2:%d,end:%d\n",begin1,end1,begin2,end2); for(int i=0;i<(end2-begin2);i++){ out[begin1+i+binarysearchfinduperrank(in,(end1-begin1),in[begin2+i],begin1)]=in[begin2+i]; } for(int i=0;i<(end1-begin1);i++){ out[begin1+i+binarysearchfindlowerrank(in,(end2-begin2),in[begin1+i],begin2)]=in[begin1+i]; } printf("\n["); for(int i=0;i<(end2-begin1);i++){ printf("%d,",out[i+begin1]); } printf("]\n"); printf("\nDATA:["); for (size_t idx = 0; idx < 11; ++idx){ printf("%d,",data[idx]); } printf("]\n"); printf("\nTMP:["); for (size_t idx = 0; idx < 11; ++idx){ printf("%d,",tmp[idx]); } printf("]\n"); } } bool myfunc (long i , long j){return (i<j);} /** * sequential MergeSort */ void MsSequential(int *array, int *tmp, bool inplace, long begin, long end) { if (begin < (end - 1)) { long half =(begin+end) / 2; MsSequential(array, tmp, !inplace, begin, half); MsSequential(array, tmp, !inplace, half, end); if (inplace){ MsMergeSequential(array, tmp, begin, half, half, end, begin,array,tmp); } else { MsMergeSequential(tmp, array, begin, half, half, end, begin,array,tmp); } } else if (!inplace) { tmp[begin] = array[begin]; printf("\n[%d]\n",tmp[begin]); printf("\nDATA:["); for (size_t idx = 0; idx < 11; ++idx){ printf("%d,",array[idx]); } printf("]\n"); printf("\nTMP:["); for (size_t idx = 0; idx < 11; ++idx){ printf("%d,",tmp[idx]); } printf("]\n"); } } /** * Serial MergeSort */ void MsSerial(int *array, int *tmp, const size_t size) { MsSequential(array, tmp, true, 0, size); } /** /** * #brief program entry point */ int main(int argc, char* argv[]) { // variables to measure the elapsed time struct timeval t1, t2; double etime; // expect one command line arguments: array size if (argc != 2) { printf("Usage: MergeSort.exe <array size> \n"); printf("\n"); return EXIT_FAILURE; } else { size_t stSize = strtol(argv[1], NULL, 10); int *data2 = (int*) malloc(stSize * sizeof(int)); int *tmp = (int*) malloc(stSize * sizeof(int)); int *ref = (int*) malloc(stSize * sizeof(int)); printf("Initialization...\n"); srand(95); for (size_t idx = 0; idx < stSize; ++idx){ data2[idx] = (int) (stSize * (double(rand()) / RAND_MAX)); } stSize=103; int data[103]{1919243808,365,372,383,394,404,413,170931,667182,540028976,741551154,774455913,774778478,778265971,840969273,892416309,942815278,1292503603,1667851881,1869182049,1919243808,35,20,20,50,50,52,53,54,54,55,55,58,63,64,64,65,388,401,65,71,73,73,74,75,75,77,289,290,290,292,300,303,308,308,308,267,312,312,314,314,315,323,323,325,330,332,333,338,339,347,347,361,221,372,383,394,404,331,331,413,2,741551154,892416309,875310137,808531502,540028976,778265971,1919243808,1667851881,1869182049,774778478,1292503603,774455913,667182,356,359,361,362,363,364,365,741684787}; std::copy(data, data + stSize, ref); printf("START"); printf("\n["); for (size_t idx = 0; idx < stSize; ++idx){ printf("%d,",ref[idx]); } printf("]\n"); printf("]"); double dSize = (stSize * sizeof(int)) / 1024 / 1024; printf("Sorting %zu elements of type int (%f MiB)...\n", stSize, dSize); gettimeofday(&t1, NULL); MsSerial(data, tmp, stSize); gettimeofday(&t2, NULL); etime = (t2.tv_sec - t1.tv_sec) * 1000 + (t2.tv_usec - t1.tv_usec) / 1000; etime = etime / 1000; printf("done, took %f sec. Verification...", etime); printf("\n["); for (size_t idx = 0; idx < stSize; ++idx){ printf("%d,",ref[idx]); } printf("]\n"); printf("\n["); for (size_t idx = 0; idx < stSize; ++idx){ printf("%d,",data[idx]); } printf("]\n"); if (isSorted(ref, data, stSize)) { printf(" successful.\n"); } else { printf(" FAILED.\n"); } printf("\n["); for (size_t idx = 0; idx < stSize; ++idx){ printf("%d,",ref[idx]); } printf("]\n"); free(data2); //delete[] data; free(tmp); //delete[] tmp; free(ref); //delete[] ref; } return EXIT_SUCCESS; }
The array ref has the size of the array data2, therefore there are more values in the array ref than in the array data and therefore when sorting the array ref it also looks at other values different from the input array
Infinite computation of qsort
i am realsing qsort algorithm, according on Korman. But there is infinite computation, when i trying to start it. I suppose, that problem is in partition. My programms reads from file, first number in file-line is counting of numbers to sort, and next go all numbers #include <stdio.h> #include <stdlib.h> int swap(int &a, int &b); int sorting(int *array, int &b, int &l); int partition(int *array ,int &begin, int &last); int main() { FILE* pFile=fopen("input.txt", "r"); //fopen("input.txt", "r"); //fopen("output.txt", "w"); int n; int begin=0; fscanf(pFile, "%d", &n); int* array=(int*)malloc(n*sizeof(int)); for (int i=0; i<n; ++i) fscanf(pFile,"%d", &array[i]); int n1=n-1; sorting(array, begin, n1); printf("JJJJ"); for (int i=0; i<n; ++i) printf("%d ", array[i]); printf("\n"); fclose(pFile); free(array); return 0; } int sorting(int* array, int &b, int &l) { int pivot,pivot1; if(b<l) { pivot=partition(array, b, l); printf("MAXMAX321"); int a=pivot-1; sorting(array, b, a); printf("MAXMAX123"); pivot1=pivot+1; sorting(array, pivot1, l); printf("MAXMAX"); } return 0; } int partition(int* array, int &b, int &l) { int x=array[b]; int i=b; int j=l; while(true) { while(array[j]>x){ printf("AHAH"); --j; } while(array[i]<x){ printf("AZAZA"); ++i; } if(i<j) swap(array[i],array[j]); else return j; } } int swap(int &x, int &y) { x=x+y; y=x-y; x=x-y; return 0; } Thank you in advance.
This part is very dangerous code: while(true) { while(array[j]>x){ printf("AHAH"); --j; } while(array[i]<x){ printf("AZAZA"); ++i; } if(i<j) swap(array[i],array[j]); else return j; } Avoid while (true) as much as possible, except on very special case you should have a clear condition stated in the loop. Here it is the one that leads to `return. It will clarify the goal of the loop. When testing array value like while(array[i]<x) compare i to the array size before ! You're never sure that you condition will always be met in the array, ensure you have a safety belt.
I cannot understand what you are doing in function partition but doing it like this should work: int partition(int* array, int &b, int &l) { int pivot_index = l;//You can take here everything between b and l //swap(array[l], array[pivot_index]); decomment this if your pivot is between b and l int current_pos = b; for(int i = b;i < l - 1; ++i) if(array[i] <= array[pivot_index]) swap(array[i], array[current_pos++]); swap(array[l], array[current_pos]); return current_pos; }
Qsort strange behaviour c++
here is my code of qsort in c++. #include <stdio.h> void partition(int* arr, int start, int pivot, int end){ int i=start+1; for(int j=start+1; j < end; j++){ if (arr[j]<pivot){ int c=arr[i]; arr[i]=arr[j]; arr[j]=c; i++; } } int c=arr[start]; arr[start]=arr[i-1]; arr[i-1]=c; } void qsort(int *arr, int start, int end, int len){ if (len<=1){ // break; } else{ int pivot=arr[start]; partition(arr, start, pivot, end); qsort(arr, start, pivot-1, len-1); qsort(arr, pivot+1, end, len-1); } } int main(){ int len; printf("Vvedite kolvo elementov"); scanf("%d", &len); int *arr=new int[len]; for(int i=0;i<len; i++){ printf("\n Vvedite %d element", i); scanf("%d", &arr[i]); } qsort(arr, 0, len, len); for(int i=0; i<len; i++){ printf(" %d, ", arr[i]); } delete [] arr; return 0; } But it has very strange output. For example - it works ok on "5 1 2 4 3" and sorts it, but when i for example type "998 603 805 990 900" that in theory absolutly the same for computer, it prints all 0. Any suggestions on how to identify/fix the problem are greatly appreciated.
Multiplying 2 matrices using pointers
so I am trying to figure out how to multiply 2 matrices using pointers. It successfully works the way it is now, but instead of using conventional array access methods, I would like to learn the use of pointers. Here is my code: #include <stdio.h> #include<conio.h> #include <stdlib.h> #include <iostream> /* Routines called. */ int loadMatrixFromFile(char *filename, int *data); void showMatrix(int *data, int len); int makeIdent(int matrixB[5][5], int length); int matrixA[5][5]; int matrixB[5][5]; int matrixC[5][5]; void multiplyMatrices(int matrixA[5][5], int matrixB[5][5],int matrixC[5][5]); int main(){ int len, data[1000]; len = loadMatrixFromFile("Numbers.txt", data); showMatrix(data, len); makeIdent(matrixB,len); multiplyMatrices(matrixA, matrixB, matrixC); } int makeIdent(int matrixB[5][5], int len){ int i,j; printf("Matrix B is: \n"); for(i=0;i<5;i++){ for(j=0;j<5;j++){ if(i==j){ matrixB[i][j]=1; printf("%d ",matrixB[i][j]); } else{ matrixB[i][j]=0; printf("%d ",matrixB[i][j]); } } printf("\n"); } return matrixB[i][j]; printf("\n"); } int loadMatrixFromFile(char *filename, int *data){ FILE *in; int len; int j; in = fopen(filename, "r"); if (in == NULL) { printf("Could not find file: %s \n", filename); } else { printf("Reading numbers...\n"); fscanf(in, "%d", &len); printf("reading %d numbers from file %s ....\n", len, filename); for(j=0;j<len;j++) { fscanf(in, "%d", data + j); } fclose(in); } for(int i = 0; i<5; i++){ for(int j = 0; j < 5; j++){ matrixA[i][j] = *(data + i*5 + j); } } return len; } void showMatrix(int *data, int len){ int j; int count = 0; printf("Showing %d numbers from data array....\n", len); printf("Matrix A is: \n"); for(j=0;j<len;j++) { printf("%d ", *(data + j)); count++; if(count % 5 == 0){ printf("\n"); } } printf("\n"); } void multiplyMatrices(int matrixA[5][5], int matrixB[5][5],int matrixC[5][5]){ int i, n, j; int count = 0; printf("\n"); printf("Matrix A x Matrix B is: \n"); for (i = 0; i<5; i++){ for (j = 0; j<5; j++){ matrixC[i][j] = 0; matrixC[i][j] += matrixA[i][j]*matrixB[i][j]; printf("%d ",matrixC[i][j]); count++; if(count % 5 == 0){ printf("\n"); } } } }
Well your algorithm for matrix multiplication is completely wrong. You say 'I want to learn how to do it with pointers', but here's the thing, you're already are doing it with pointers. In this code void multiplyMatrices(int matrixA[5][5], int matrixB[5][5],int matrixC[5][5]){ the variables matrixA, matrixB and matrixC are pointers. In C++ it's impossible to have an array for a function parameter. It automatically gets converted to a pointer. It's also true that the syntax for accessing an array is identical to the syntax for accessing a pointer. If you want to make it explicit that you are using pointers then rewrite your code like this void multiplyMatrices(int (*matrixA)[5], int (*matrixB)[5],int (*matrixC)[5]){ Now you can see that matrixA, matrixB and matrixC pointers to arrays of 5 integers. You don't have to make any other changes. And in fact this change is exactly what the compiler does when you try to use an array as a function parameter. Here's a good looking link that explains how pointers and arrays compare. The link talks about C, but the rules are the same in C++. Have a read it will probably help you understand better than I can.