Creating a matrix and free() problems - c - c

it seems i have some problems in my code. the first one is that i cant use the free function correctly:"heap corruption detected".
in the second part of my work i wanted to create a matrix:it puts a red mark under the j and then the compiler says that subscript requires array and pointer type.
i only wanted to create a two dimension matrix.
thanks for your help!!!
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <math.h>
void main()
{
char *word[1000] = { 0 }, letter[1000], *temparr, *originalarr;
int i = 0, j = 0, counter = 0, k = 0, w = 0, anagram = 0, size = 0, *mat;
for (i = 0; letter[i] != '\n'; i++)
{
letter[i] = getchar();
counter++;
if (letter[i] == ' ' || letter[i] == '\n')
{
if (letter[i] == 10)
{
letter[i] = 0;
word[j] = malloc(sizeof(char*)*(counter - 1));
strcpy_s(word[j], (counter - 1) * sizeof(char*), &letter[i - (--counter)]);
break;
}
if (letter[i - 1] == ' ')
continue;
letter[i] = '\0';
word[j] = malloc(sizeof(char*)*counter);
strcpy_s(word[j], (counter - 1) * sizeof(char*), &letter[i - (--counter)]);
letter[i] = ' ';
counter = 0;
j++;
}
}
while (j > 0)
{
printf_s("%s ", word[j--]);
if (j == 0)
printf_s("%s", word[j]);
}
for (j = 0; word[j] != 0; j++)
{
originalarr = (char*)malloc((sizeof(char) * strlen(word[j])));
strcpy_s(originalarr, strlen(word[j]) + 1, word[j]);
for (i = 0; word[i] != 0; i++)
{
temparr = (char*)malloc((sizeof(char) * strlen(word[i])));
strcpy_s(temparr, strlen(word[i]) + 1, word[i]);
counter = 0;
if (strlen(originalarr) != strlen(temparr))
continue;
for (k = 0; originalarr[k] != 0; k++)
{
for (w = 0; w < strlen(temparr); w++)
{
printf_s("temparr - %c ", temparr[w]);
printf_s("original - %c\n", originalarr[k]);
if (originalarr[k] == temparr[w])
{
temparr[w] = '0';//problem, but cant be equal to 0
counter++;
printf_s("counter- %d\n", counter);
}
}
}
if (counter == strlen(originalarr))
anagram++;
free(temparr);//problem
}
}
k = 0;
size = ceil(sqrt(strlen(letter)));
mat = (int*)malloc((sizeof(int) * size));
for (i = 0; i < size; i++)
{
mat[i] = (int)malloc((sizeof(int) * size));
for (j = 0; j < size; j++)
mat[i][j] = '\0';
}
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
{
mat[i][j] = letter[k];
k++;
}
}

For the second part of your question you need to declare a pointer to a pointermat instead of a simple pointer as you have done. Then allocate as shown.
int ** mat;
mat = malloc((sizeof(int*) * size));
for (i=0; i<size; i++)
mat[i] = malloc( sizeof(int) * size));
You can use this array mat as a 2D array mat[i][j]

Related

Find all Palindromes in a String Using C

I am trying to use C to print all Palindromes in a string and return the total number.
My code is returning all sorts of substrings which are not palindromes and printing blanks.
I am off by at least one in my printf statement formatting, but also, in my array element comparisons, it is working the opposite as I intended.
Can anyone see where I am going wrong?
Here is my code:
#include<stdio.h>
#include<string.h>
char x[1000];
void getString(char *n)
{
printf("\nPlease enter your string: ");
scanf("%s", n);
}
int findPals(char *s)
{
int length = strlen(s);
int numPals = 0;
//find odd palindromes
for(int i = 0; i < length; i++)
{
for(int j = 0; j + i < length && i - j >= 0; j++)
{
if(s[i + j] != s[i - j])
continue;
else
{
numPals++;
printf("%.*s\n", (j - i),s + i);
}
}
}
//find even palindromes
for(int i = 0; i < length; i++)
{
for(int j = 0; j + i + 1 < length && i - j >= 0; j++)
{
if(s[i + j + 1] != s[i - j])
continue;
else
{
numPals++;
printf("%.*s\n", (j - i),s + i);
}
}
}
return numPals;
}
int main()
{
char inStr[1000];
int totalPals;
getString(inStr);
totalPals = findPals(inStr);
printf("I found %d palindromes.\n", totalPals);
return 0;
}
There are only 2 small corrections required in your code (given below) other than that everything is fine:-
1.Continue statement in the array checking should be changed to break:
for(int i = 0; i < length; i++)
{
for(int j = 0; j + i < length && i - j >= 0; j++)
{
if(s[i + j] != s[i - j])
break; // continue statement has been changed to break;
else
{
numPals++;
printf(".*s\n",(2*j)+1,&s[i-j]); // The length of the string has been modified
}
}
}
The string length in printf is incorrect.
For odd section use:
printf(".*s\n",(2*j)+1,&s[i-j]);
And for even section use:
printf(".*s\n",(2*j)+2,&s[i-j]);
Thanks for the help. Here is my final program.
#include<stdio.h>
#include<string.h>
char x[1000];
void getString(char *n)
{
printf("\nPlease enter your string: ");
scanf("%s", n);
}
int findPals(char *s)
{
int length = strlen(s);
int numPals = 0;
//find odd palindromes
for(int i = 0; i < length; i++)
{
for(int j = 0; j + i < length && i - j >= 0; j++)
{
if(s[i + j] != s[i - j])
break;
else
{
if ((j + j) > 1)
{
numPals++;
printf("%.*s\n", ((2 * j) + 1), &s[i - j]);
}
}
}
}
//find even palindromes
for(int i = 0; i < length; i++)
{
for(int j = 0; j + i + 1 < length && i - j >= 0; j++)
{
if(s[i + j + 1] != s[i - j])
break;
else
{
if ((j + j) > 1)
{
numPals++;
printf("%.*s\n", ((2 * j) + 2), &s[i - j]);
}
}
}
}
return numPals;
}
int main()
{
char inStr[1000];
int totalPals;
getString(inStr);
totalPals = findPals(inStr);
printf("I found %d palindromes.\n", totalPals);
return 0;
}

Replacing repeated values in an array in C

I'm coding a function in C to check if an array has any duplicate value, and if so replace it by any of the non-present ones. The array consists of numbers shuffled from 1 to Nmax:
unsigned char * NotRepeated (unsigned char *arr){
unsigned char i, j, count, k, notrepeated[Nmax];
k = 0;
for (i = 0; i < Nmax ; i++){
count = 0;
for (j = 0; j < Nmax; j++){
if (arr[j] != i + 1){
count++;
}
if (count == Nmax){
notrepeated[k] = i + 1;
k++;
}
}
}
k = 0;
for (i = 0; i < Nmax - 1; i++){
for (j = i + 1; j < Nmax; j++){
if (arr[i] == arr[j]){
arr[j] = notrepeated[k];
k++;
}
}
}
return arr
}
If I print the array notrepeated[k] I get almost all the array filled when the original array arr[j] seldomly has more than 2 repeated figures.
What am I doing wrong?
Thanks!

Can't compile matrix multiplication

Hey I got this error and I tried like 10 solutions and neither works. I want to load 2 matrix, each one from its own txt file then to multiply them. I can't compile cause of LNK1120 and LNK2019 errors.
Here is my code:
int main(int argc, char *argv[])
{
FILE *macierz1, *macierz2, *fw;
char *line = malloc(1000);
int count = 0;
macierz1 = fopen("macierz1.txt", "r");
if (macierz1 == NULL) {``
printf("nie można otworzyć", argv[1]);
exit(1);
}
macierz2 = fopen("macierz2.txt", "r");
if (macierz2 == NULL) {
printf("nie można otworzyć", argv[2]);
exit(1);
}
double *data = (double*)malloc(1000 * sizeof(double));
if (data == NULL)
{
printf("błąd lokowania pamięci");
return EXIT_FAILURE;
}
getline(&line, &count, macierz1);
int read = -1, cur = 0, columCount1 = 0;
while (sscanf(line + cur, "%lf%n", &data[columCount1], &read) == 1)
{
cur += read; columCount1++;
}
int rowCount1 = 1;
while (getline(&line, &count, macierz1) != -1) { rowCount1++; }
printf("%d\n", columCount1);
printf("%d\n", rowCount1);
getline(&line, &count, macierz2);
read = -1, cur = 0;
int columCount2 = 0;
while (sscanf(line + cur, "%lf%n", &data[columCount2], &read) == 1)
{
cur += read; columCount2++;
}
int rowCount2 = 1;
while (getline(&line, &count, macierz2) != -1) { rowCount2++; }
printf("%d\n", columCount2);
printf("%d\n", rowCount2);
int i = 0;
int j = 0;
int **mat1 = (int **)malloc(rowCount1 * sizeof(int*));
for (i = 0; i < rowCount1; i++)
mat1[i] = (int *)malloc(columCount1 * sizeof(int));
fseek(macierz1, 0, SEEK_SET);
for (i = 0; i < rowCount1; i++)
{
for (j = 0; j < columCount1; j++)
fscanf(macierz1, "%d", &mat1[i][j]);
}
i = 0;
j = 0;
printf("\n\n");
//print matrix 1
for (i = 0; i < rowCount1; i++)
{
for (j = 0; j < columCount1; j++)
printf("%d", mat1[i][j]);
printf("\n");
}
i = 0;
j = 0;
int **mat2 = (int **)malloc(rowCount2 * sizeof(int*));
for (i = 0; i < rowCount2; i++)
mat2[i] = (int *)malloc(columCount2 * sizeof(int));
fseek(macierz2, 0, SEEK_SET);
for (i = 0; i < rowCount2; i++)
{
for (j = 0; j < columCount2; j++)
fscanf(macierz2, "%d", &mat2[i][j]);
}
i = 0;
j = 0;
printf("\n\n");
//print matrix 2
for (i = 0; i < rowCount2; i++)
{
for (j = 0; j < columCount2; j++)
printf("%d", mat2[i][j]);
printf("\n");
}
i = 0;
int **mat3 = (int **)malloc(rowCount1 * sizeof(int*));
for (i = 0; i < rowCount1; i++)
mat3[i] = (int *)malloc(columCount2 * sizeof(int));
i = 0;
j = 0;
int k = 0;
int sum = 0;
if (columCount1 != rowCount2)
{
puts("The number of columns in Matrix 1 is not same as the number of rows in Matrix 2");
exit(1);
}
//multiplication of two matrices
for (i = 0; i<rowCount1; i++)
{
for (j = 0; j<columCount2; j++)
{
mat3[i][j] = 0;
for (k = 0; k<columCount1; k++)
{
mat3[i][j] = mat3[i][j] + mat1[i][k] * mat2[k][j];
}
}
}
//print multiplication result
printf("\n\nResult = \n\n");
for (i = 0; i < rowCount1; i++)
{
for (j = 0; j < columCount2; j++)
printf("%d", mat3[i][j]);
printf("\n");
}
for (i = 0; i< rowCount1; i++)
free(mat1[i]);
free(mat1);
for (i = 0; i< rowCount2; i++)
free(mat2[i]);
free(mat2);
for (i = 0; i< rowCount1; i++)
free(mat3[i]);
free(mat3);
free(data);
return 0;
}
Since you're using Visual C++, there is no such C function as getline. The C compiler that comes with Visual C++ adheres to the C89 specification.
Use fgets to retrieve the data from the file.
If you really want to use getline in your Visual C++ (really C) program, you could try this code from GNU that implements the function.
There is a stray '`' in program posted at the end of the line:
if (macierz1 == NULL) {``
and
getline
function is not defined.
add needed includes:
#include <stdio.h>
#include <stdlib.h>

C: Finished Tic Tac Toe program, looking for tips to improve it

I have finished up my code since last time(thanks to everyone's help!).
I'm not 100 % sure that your code is supposed to be a complete game, but I can change the return values so that your code compiles and starts the Tic-Tac-Toe.
#include <stdio.h>
#include <stdlib.h>
char **display_board(char **board) { //Create board function
const char NUM_COLS = 3;
const char NUM_ROWS = 3;
const char BLANK_SPACE = '*';
int i, j, k, l;
board = (char **) malloc(NUM_ROWS * sizeof(char *));
for (i = 0; i < NUM_ROWS; i++) {
board[i] = (char *) malloc(NUM_COLS * sizeof(char));
for (j = 0; j < NUM_COLS; j++) {
board[i][j] = BLANK_SPACE;
}
//Display board function
}
for (k = 0; k < NUM_ROWS; k++) {
for (l = 0; l < NUM_ROWS; l++) {
printf("%c", board[k][l]);
}
printf("\n");
}
return board;
}
int main() {
char **board;
int row, col;
const char BLANK_SPACE = '*';
int turn, i;
turn = 0;
display_board(board);
//need while !game_not_over conditional statement
for (i = 0; i < 20; i++) {
turn + 1;
}
if (turn % 2 == 0) {
printf("O's turn\n");
printf("Make your move");
scanf("%d, %d", &row, &col);
if ((row == 0 && col == 0) && (board[0][0] == BLANK_SPACE)) {
display_board(board);
board[0][0] = '0';
}
return 0;
}
}
Test
Debug/gnu
***
***
***
O's turn
Make your move***

Switching rows of two dimensional arrays in c

At the moment I'm wondering how can I swap the values already in a two dimensional array, in this case I managed to swap them, however, I can't seem to be able to swap them back... How can I make a program swap the values back and forward for the array?
Code:
#include <stdio.h>
void main()
{
//declaration of values
int d = 0;
char value;
float list[5][6], swaplist[5][6];
float average_odd, sum = 0, average_even, sum1 = 0;
//Command list so that the user knows what he can do in this program
printf("Command list:\t \n\nCommand: \t\t Output: ");
printf("\n \"A\" \t\t Declare values of a list.\n \"O\" \t\t Obtain the average value of the even and odd column\n\t\t values in the list.\n");
printf(" \"I\" \t\t Exchange the values on the even columns with the odd ones.\n \"P\" \t\t Print the values of the list.\n \"S\" \t\t End program.");
//========================================================================================================
while (d != 1)
{
printf("\n\nInsert value: ");
scanf(" %c", &value);
//=========================================================================================================
if (value == 'a' || value == 'A')
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 6; j++)
{
printf("Insert value of element %d in column %d: ", i + 1, j + 1);
scanf("%f", &list[i][j]);
swaplist [i][j] = list[i][j];
}
}
}
//=========================================================================================================
if (value == 's' || value == 'S')
{
d++;
}
//=========================================================================================================
if (value == 'P' || value == 'p')
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 6; j++)
{
printf("%2.2f ", list[i][j]);
}
printf("\n");
}
}
//========================================================================================================
if (value == 'o' || value == 'O')
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 6; j = j + 2)
{
sum += list[i][j];
}
}
for (int i = 0; i < 5; i++)
{
for (int j = 1; j < 6; j = j + 2)
{
sum1 += list[i][j];
}
}
average_even = sum1 / 15;
printf("The average of the even columns = %.2f\n", average_even);
average_odd = sum / 15;
printf("The average of the odd columns = %.2f\n", average_odd);
}
//=======================================================================================================
if (value == 'i' || value == 'I')
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 6; j = j + 2)
{
list[i][j] = swaplist[i][j+1];
}
}
for (int i = 0; i < 5; i++)
{
for (int j = 1; j < 6; j = j + 2)
{
list[i][j] = swaplist[i][j - 1];
}
}
}
}
}
After swapping, you don't change the state of the swap list. At first, the swap list is a copy of the unswapped matrix. You don't change it to reflect the changes in the matrix and don't keep track of any other state.
You don't really need the swap list. I suggest that you just do a regular swapping of adjacent columns cell by cell:
if (value == 'i' || value == 'I') {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j = j + 2) {
float swap = list[i][j];
list[i][j] = list[i][j + 1];
list[i][j + 1] = swap;
}
}
}
That will toggle the matrix on repeated swaps.

Resources