C: 2d char array issue - c

i've a problem with an exercise. The purpose is to print a specific picture after an int input (It is assumed that the input is > 3).
Example:
https://i.stack.imgur.com/KRl0R.png
This is my code:
#include <stdio.h>
int main(void){
int i, j, n, simbolo;
printf("Inserire un numero: ");
scanf("%d", &n);
char mat[n + 1][n + 2];
simbolo = n+2;
//initialization with blank space and setting 3 * diagonal
for(i = 0; i < n + 1; i ++){
for(j = 0; j < n + 2; j++){
mat[i][j] = ' ';
mat[n - 2][0] = '*';
mat[n - 1][1] = '*';
mat[n][2] = '*';
}
}
//Add * diagonal of n length
for(i = 0; i < n + 1; i++){
mat[i][simbolo] = '*';
for(int x = i, y = 0; y < n + 2; y++){ //Print current line
printf("%c", mat[x][y]);
}
printf("\n");
simbolo--;
}
return 0;
}
The output isn't correct, it's added an extra '*' in mat[1][0]:
https://i.stack.imgur.com/4Z5Fl.png
Thanks in advance for you help

According to image, you want your output to have n rows, not n+1. This works correctly:
#include <stdio.h>
int main(void){
int i, j, n, simbolo;
printf("Inserire un numero: ");
scanf("%d", &n);
char mat[n][n + 2];
simbolo = n+1;
//initialization with blank space and setting 3 * diagonal
for(i = 0; i < n; i ++){
for(j = 0; j < n + 2; j++){
mat[i][j] = ' ';
}
}
mat[n - 3][0] = '*';
mat[n - 2][1] = '*';
mat[n - 1][2] = '*';
//Add * diagonal of n length
for(i = 0; i < n; i++){
if(i<(n-1))
mat[i][simbolo] = '*';
printf("%.*s\n", n+2, mat[i]);
simbolo--;
}
return 0;
}

Some other people have already pointed out the issue, so I thought I would just post a cleaned up version for your reference:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("n: ");
int n = 0;
if (scanf("%d", &n) != 1) {
fprintf(stderr, "ERROR: couldn't read 'n'\n");
return EXIT_FAILURE;
}
char mat[n][n + 2];
// Initialize with spaces.
int i;
int j;
for (i = 0; i < n; i++)
for (j = 0; j < n + 2; j++)
mat[i][j] = ' ';
// Draw the first 2 * on the left.
mat[n - 3][0] = '*';
mat[n - 2][1] = '*';
// Draw the diagonal on the right.
j = n + 1;
for (i = 0; j >= 2; i++, j--)
mat[i][j] = '*';
// Print out the result.
for (i = 0; i < n; i++) {
for (j = 0; j < n + 2; j++)
printf("%c", mat[i][j]);
printf("\n");
}
return EXIT_SUCCESS;
}

I just changed
mat[i][simbolo] = '*';
for
mat[i+1][simbolo-1] = '*';
I also changed the spaces for '-' to make the output clearer.
The problem is the one mentioned in the comments: your indices were off.
Remember, in C, indexing is 0 based, so the last element of any array has index n-1.
Usually, in C when you go further the pointer just goes back to the beginning.
#include <stdio.h>
int main(void){
int i, j, n, simbolo;
printf("Inserire un numero: ");
scanf("%d", &n);
char mat[n + 1][n + 2];
simbolo = n+2;
//printf("Simbolo: %d",simbolo);
//initialization with blank space and setting 3 * diagonal
for(i = 0; i < n + 1; i ++){
for(j = 0; j < n + 2; j++){
mat[i][j] = '-';
mat[n - 2][0] = '*';
mat[n - 1][1] = '*';
mat[n][2] = '*';
}
}
//Add * diagonal of n length
for(i = 0; i < n+1 ; i++){
mat[i+1][simbolo-1] = '*';
for(int y = 0; y < n + 2; y++){ //Print current line
//printf(",x< %d, y: %d",i,y);
printf("%c", mat[i][y]);
}
printf("\n");
//printf("Simbolo: %d",simbolo);
simbolo--;
}
return 0;
}

Related

utf-8 codec can't decode byte 0x87 in position 377: invalid start byte

The program is to accept a matrix and an integer and replace all the elements with asterisk('*') other than the elements present in upper left and right triangle and lower right and left triangle of size k.
code:
#include <stdio.h>
int main()
{
int n, x, i, j;
// Inputs
printf("n: ");
scanf("%d\n", &n);
char a[n][n], b[n][n];
printf("Enter the matrix elements\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("[%d][%d]: ", i, j);
scanf("%c\n", &a[i][j]);
b[i][j] = '*';
}
}
printf("x: ");
scanf("%d\n", &x);
printf("x: %d\n",x);
// Implementation
// Top right and left triangles
for (i = 0; i < n; i++)
{
for (j = 0; j < x - i; j++)
{
b[i][j] = a[i][j];
}
for (j = n - 1; j >= (n - x) + i; j--)
{
b[i][j] = a[i][j];
}
}
// Bottom right and left triangles
int c = 0;
for (i = n - 1; i >= (n - x); i--)
{
for (j = 0; j < x - c; j++)
{
b[i][j] = a[i][j];
}
for (j = n - 1; j >= (n-x) + c; j--)
{
b[i][j] = a[i][j];
}
c++;
}
// Printing the mat
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%c ", b[i][j]);
}
printf("\n");
}
return 0;
}
The program works for inputs 1 through 8... I didn't try for inputs past 8 because its was tedious enough to type 64 elements, but when I submitted the program it showed that for test case of matrix size 50 the result was an error, specifically 'utf-8' codec can't decode byte 0x87 in position 377: invalid start byte
The program works fine for inputs 1 to 8. Any idea why this is happening?

Changing 6 different random numbers with SRAND in a board made with Dynamically Allocated Arrays

So, I have a code that creates a 7x7 board with Dynamically Allocated Arrays and inside of a board is full with "?" and what I want to do is creating a new function and inside a function, I used rand command to get random numbers like this,
int random() {
return ((rand() % 7) + 1);
}
Therefore, I had a problem changing 6 random numbers in a board and my Code is below,
This one below is the one I tried to get random numbers for an Array,
printf("Enter number: ");
scanf("%d", &b);
char *rando = (char *)malloc(7 * 7 * sizeof(char));
for (i = 0; i < b; i++) {
rand1 = random();
rand2 = random();
*(rando + rand1 + rand2) = '*';
}
And this one is where I printed the "?" signs and also where I tried to change 6 different signs and it only prints out "else" part ignoring the "if" for some reason
for (j = 0; j < 7; j++) {
if (*(board + i + j) == *(rando + i + j))
printf("| %c ", *(rando + i + j));
else
printf("| %c ", *(board + i + j));
}
And my whole code is this, it's kinda long but most of them are for a nice looking board
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int random() {
return ((rand() % 7) + 1);
}
int main() {
int i, j, k, rand1, rand2, b;
srand(time(NULL));
printf("Enter number: ");
scanf("%d", &b);
char *rando = (char *)malloc(7 * 7 * sizeof(char));
for (i = 0; i < b; i++) {
rand1 = random();
rand2 = random();
*(rando + rand1 + rand2) = '*';
}
char *board = (char *)malloc(7 * 7 * sizeof(char));
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
*(board + i + j) = '?';
}
}
for (i = 1; i <= 7; i++) {
printf("%4d", i);
}
printf("\n ");
for (i = 0; i < 7; i++) {
printf("+---");
}
printf("+\n");
for (i = 0; i < 7; i++) {
printf("%d ",i);
for (j = 0; j < 7; j++) {
if (*(board + i + j) == *(rando + i + j))
printf("| %c ", *(rando + i + j));
else
printf("| %c ", *(board + i + j));
}
printf("|\n");
for (k = 0; k <= 7; k++)
if (k == 0)
printf(" ");
else
printf("+---");
printf("+\n");
}
}
I pointed out important parts that I'm stuck with but still not sure if there is a problem in other parts of my code so I showed it here, just in case.
There are multiple problems in your code:
you allocate the 7x7 matrix as a single array of 49 characters. Yet you do not index into this array with the correct formula. The element at position (i,j) is accessed as *(board + 7 * i + j), not *(board + i + j).
It would be simpler to declare rando and board to point to a 2D matrix and use the [] syntax:
char (*board)[7] = malloc(7 * sizeof(*board));
and use board[i][j].
Furthermore, the rando array is uninitialized, so the program has undefined behavior when reading the contents of the elements that have not been set to '*' in the first loop. You must initialize this array with '?'. You can do this with memset().
the function random() returns an integer in the range 1 to 7 inclusive. You should instead compute pseudo-random coordinates in the range 0 to 6. Remove the +1;
the test in the board printing loop is useless: if the board element at position i,j is the same as in the rando matrix you print the rando element otherwise t board element. This always prints the board element.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int random(void) {
return rand() % 7;
}
void init_board(char board[7][7]) {
// board can be initialized with 2 nested loops or
// a single call to
//memset(board, '?', 7 * 7);
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
board[i][j] = '?';
}
}
}
void print_board(char board[7][7]) {
for (int i = 0; i < 7; i++) {
printf("%4d", i + 1);
}
printf("\n ");
for (int i = 0; i < 7; i++) {
printf("+---");
}
printf("+\n");
for (int i = 0; i < 7; i++) {
printf("%d ", i + 1);
for (int j = 0; j < 7; j++) {
printf("| %c ", board[i][j]);
}
printf("|\n");
printf(" ");
for (int j = 0; j < 7; j++) {
printf("+---");
}
printf("+\n");
}
}
int main() {
int b;
srand(time(NULL));
printf("Enter number: ");
scanf("%d", &b);
char (*rando)[7] = malloc(7 * sizeof(*rando));
if (!rando)
return 1;
init_board(rando);
for (int i = 0; i < b; i++) {
int rand1 = random();
int rand2 = random();
rando[rand1][rand2] = '*';
}
char (*board)[7] = malloc(7 * sizeof(*board));
if (!board)
return 1;
init_board(board);
/* print the mines */
print_board(rando);
/* print the board */
print_board(board);
free(rando);
free(board);
return 0;
}

Why triple nested for loop doesn't work the 2nd time in C?

Edid: Thanks for the suggestions, but none of them work for the FOR loop error.
Why the triple nested for loop(line 82 - 98) works only the first time(correctly) and then it just spits crazy random numbers? The first time it works so good and then it does everything wrong. Thanks for the help!
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
// 2 players, 5 zara, 3 puti(ako ne si gi haresa), moje da pazite:
//1 qift
// 2 qifta
// ful: 1*2 i 1*3
// 5 ednakvi: general
// 4 ednakvi
// 1*3
// 5 poredni
// shans
// izpulnqvase 8 puti i moje da se zapazva zara (samo pri 1 i 2 hvurlane)
int np, otg[5], otg10[5];
int check_pairs(int *otg10, int time){
int dicecopy[5];
memcpy(dicecopy, otg10, sizeof(int) * 5);
for(int k = 0; k < 5; k++){
printf("%d " , dicecopy[k]);
}
int pairs = 0, sum = 0;
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
if(dicecopy[i] == dicecopy[j])
pairs++;
}
}
// points
if(pairs == 1*2 || pairs == 2*2){
printf("GGGGGGG");
for(int k = 0; k < 5; k++){
sum += dicecopy[k];
}
} else {
return 0;
}
return sum;
}
int main(){
printf("How many players do you want: ");
scanf("%d" , &np);
int points[np];
for(int i = 0; i < np; i++){
points[i] = 0;
}
int dice[8][np][3][5];
srand(time(NULL));
for(int i = 0; i < 8; i++){
for(int j = 0; j < np; j++){
for(int c = 0; c < 3; c++){
for(int k = 0; k < 5; k++){
dice[i][j][c][k] = rand() % 6 + 1;
}
}
}
}
/* for(int i = 0; i < 8; i++){
for(int j = 0; j < np; j++){
for(int c = 0; c < 3; c++){
for(int k = 0; k < 5; k++){
printf("%d " , dice[i][j][c][k]);
}
putchar('\n');
}
putchar('\n');
}
putchar('\n\n');
}
*/
char anws = 'y';
for(int i = 0; i < 8; i++){
for(int j = 0; j < np; j++){
printf("\nPlayer: %d\nPoints: %d\n" , j + 1 , points[j]);
for(int k = 0; k < 3; k++){
for(int l = 0; l < 5; l++){
otg10[l] = dice[i][j][k][l];
printf("%d " , otg10[l]);
}
printf("\n\nDo you like it?\n");
scanf("%s" , &anws);
if(anws == 'y' || anws == 'Y'){
points[j] = check_pairs(otg10 , k);
break;
}
}
}
}
return 0;
}
The code is still not finished I have to do more work on the other check-ups. BTW this will represent the game called Generala, if you have any suggestions I'd like to hear them!

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;
}

#EMERGENCY!!! Run-Time Check Failure #2 - Stack around the variable 'b' was corrupted

I know this seems like an old question, but none answered questions I searched work.
I have kept receiving "Run-Time Check Failure #2 - Stack around the variable 'b' was corrupted." when I was trying to do a [4][2]*[2][3] matrix multiplication.
Does anyone spot the problem?
#include <stdio.h>
int main() {
int a[4][2] = {0};
int b[2][3] = {0};
int c[3][3] = {0};
int i, j;
printf("Please enter first matrix value\n");
for (i = 0; i < 4; i++) {
for (j = 0; j < 2; j++) {
printf("%d row, %d column:", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
}
printf("Please enter second matrix value\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d row, %d column:", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
}
printf("\n the result is :\n");//
for (i = 0; i < 4; i++) {
printf("[");
for (j = 0; j < 3; j++) {
c[i][j] = (a[i][0] * b[0][j]) + (a[i][1] * b[1][j]);
printf(" %4d ", c[i][j]);
}
printf("]\n");
}
return 0;
}
I haven't checked your code thoroughly, but you define c as 3x3, and here
for (i = 0; i < 4; i++) {
printf("[");
for (j = 0; j < 3; j++) {
c[i][j] = (a[i][0] * b[0][j]) + (a[i][1] * b[1][j]);
...you access c[3], which is c's fourth element, and does not exist. This is bound to write somewhere else.
So check your indexes (as #ptb observed, c's should actually be four rows deep).

Resources