user3376431
user3376431

Reputation: 13

Why is my 2D array only printing out one value?

I'm making a word search program and am in the beginning steps. I'm trying to make user inputted sized grid of '+' before the user enters in the words that go into the word search. When i run the program it only prints out one '+'. Why is it only printing one value and how do i adjust my code so that every value is represented as '+'? I'm a programming beginner so any advice would be helpful..thank you.

#include<stdio.h>

void printmatrix(char matrix[][20],int);

int main(void)
{
   char matrix[20][20]= {{'+'}};
   int x=1;

       printf("How large would you like the puzzle to be (between 10 and 20):\n");

   scanf("%d",&x);

   printmatrix(matrix,x);

   return 0;

}

/********************************************

 Function Name: Printmatrix...this function prints out an empty matrix of the grid size the user asked for

 Inputs: Variables x and y...the row and column variables the user inputted

 Outputs: Empty matrix filled with '+' thats the size the user asked for

********************************************/

void printmatrix(char matrix[][20],int x)
{
   int i,j;

   printf("Empty Puzzle:\n");

   for (i=0;i<x;i++)
   {
      for (j=0;j<x;j++)
      {
          printf("%c", matrix[i][j]);
      }
      printf("\n");
   }

}

Upvotes: 1

Views: 146

Answers (2)

MikePro
MikePro

Reputation: 192

You may want to write nested loops to init the matrix chars to '+':

char matrix[20][20];
int i;
int j;

/* Fill matrix with '+' */
for (i = 0; i < 20; i++) {
    for (j = 0; j < 20; j++) {
        matrix[i][j] = '+';
    }
}

Upvotes: 1

this
this

Reputation: 5290

Since you use a char array you can use memset to set the values of the array to the same value.

memset( matrix , '+' , sizeof( matrix ) ) ;

You code

char matrix[20][20]= {{'+'}};

will only do

matrix[0][0] = '+' ;

and the rest of array will be set to 0.

Upvotes: 1

Related Questions