How to print vertically in C? - c

I have to printfs in a loop an I want to print the output in two lines, instead of intermingled on one line.
Like this:
printf("| %-7.2f ", Fahrenheit);
which produces:
| -508.00 | -463.00 | -418.00 | -373.00 | -328.00 | -283.00 |
When I add printf("| %-6d", Celsius); under the printf above, it prints right next to/in the middle of my first printf.
I want the output to be like:
| -508.00 | -463.00 | -418.00 | -373.00 | -328.00 | -283.00 |
| -300 | -275 | -250 | -225 | -200 | -175 | -150 | -125|
instead of the two sets of values being intermingled on the same line.
part of my code:
for(Celsius = CelsiusMin;Celsius <= CelsiusMax; Celsius += CelsiusStep)
{
Fahrenheit = FahrenheitZero + Celsius * CelsiusToFahrenheit;
printf("| %-7.2f ", Fahrenheit);
printf("| %-6d", Celsius);
}
return EXIT_SUCCESS;
}

You can't directly have one sequence of printf() statements writing to line 1 and a second concurrent sequence of printf() statements writing to line 2, so you're going to have to fake it.
You probably need something that builds up the two lines of output, and then prints them when they're ready:
char line1[128];
char line2[128];
char *next1 = line1;
char *next2 = line2;
for (int c = -325; c <= -125; c += 25)
{
double f = (c + 40.0) * (9.0 / 5.0) - 40.0;
next1 += sprintf(next1, "| %-7.2f ", f);
next2 += sprintf(next2, "| %-7d ", c);
}
printf("%s|\n", line1);
printf("%s|\n", line2);
Sample output:
| -553.00 | -508.00 | -463.00 | -418.00 | -373.00 | -328.00 | -283.00 | -238.00 | -193.00 |
| -325 | -300 | -275 | -250 | -225 | -200 | -175 | -150 | -125 |
The conversion formula is simpler than the usual one you see quoted, and is symmetric for converting °F to °C or vice versa, the difference being the conversion factor (9.0 / 5.0) vs (5.0 / 9.0). It relies on -40°C = -40°F. Try it:
C =  0°C; (C+40) = 40; (C+40)*9 = 360; (C+40)*9/5 = 72; (C+40)*9/5-40 = 32°F.
F = 32°F; (F+40) = 72; (F+40)*5 = 360; (F+40)*5/9 = 40; (F+40)*5/9-40 =  0°C.
You might do better with the degrees Celsius as printed as a double too; I kept the integer representation you chose, but made sure the numbers line up on the two lines.
FYI: Absolute zero is -273.15°C, 0K, -459.57°F. So you're attempting to print non-existent temperatures.

Related

How to create a responsive table using C?

I want create a responsive table using C, not C++ or C#, only the old C.
Basically, I create a multiplication table and put lines and borders using the symbols + - and |, but when I use a number with a width greater than one, they are disorganized, so I would like to know some way that, when I put this number, the lines follow it. My code, the actual output and the desired output:
int endTab, selecNum, CurrentRes;
printf("\n\t+----------------------+");
printf("\n\t| multiplication table |");
printf("\n\t+----------------------+\n\n\n");
printf("Enter the table number:");
scanf("%d", &selecNum);
printf("Enter which number will end in:");
scanf("%d", &endTab);
printf("\n\t+-------+---+\n");
// | 1 x 2 | 2 |
for (int i = 1; i <= endTab; i++){
CurrentRes = i*selecNum;
printf("\t| %d x %d | %d |\n", i, selecNum, CurrentRes);
printf("\t+-------+---+\n");
}
return 0;
current output
+----------------------+
| multiplication table |
+----------------------+
Enter the table number:1
Enter which number will end in:10
+-------+---+
| 1 x 1 | 1 |
+-------+---+
| 2 x 1 | 2 |
+-------+---+
| 3 x 1 | 3 |
+-------+---+
| 4 x 1 | 4 |
+-------+---+
| 5 x 1 | 5 |
+-------+---+
| 6 x 1 | 6 |
+-------+---+
| 7 x 1 | 7 |
+-------+---+
| 8 x 1 | 8 |
+-------+---+
| 9 x 1 | 9 |
+-------+---+
| 10 x 1 | 10 |
+-------+---+
expected output
+----------------------+
| multiplication table |
+----------------------+
Enter the table number:1
Enter which number will end in:10
+--------+----+
| 1 x 1 | 1 |
+--------+----+
| 2 x 1 | 2 |
+--------+----+
| 3 x 1 | 3 |
+--------+----+
| 4 x 1 | 4 |
+--------+----+
| 5 x 1 | 5 |
+--------+----+
| 6 x 1 | 6 |
+--------+----+
| 7 x 1 | 7 |
+--------+----+
| 8 x 1 | 8 |
+--------+----+
| 9 x 1 | 9 |
+--------+----+
| 10 x 1 | 10 |
+--------+----+
Things to note:
The output has two columns and you have to maintain width of both the columns for each row.
The maximum width of column 1 is width of selectNum x endTab including leading and trailing space character.
The maximum width of column 2 is the width of result of selectNum x endTab including leading and trailing space.
The length of separator after every row will be based on the maximum width of both the columns.
+---------------+-------+
\ / \ /
+-----------+ +---+
| |
max width max width
of col 1 of col 2
You can do:
#include <stdio.h>
#define SPC_CHR ' '
#define BIND_CHR '+'
#define HORZ_SEP_CH '-'
#define VERT_SEP_CH '|'
#define MULT_OP_SIGN 'x'
void print_label (void) {
printf("\n\t+----------------------+");
printf("\n\t| multiplication table |");
printf("\n\t+----------------------+\n\n\n");
}
void print_char_n_times (char ch, int n){
for (int i = 0; i < n; ++i) {
printf ("%c", ch);
}
}
void print_row_sep (int max_w1, int max_w2) {
printf ("\t%c", BIND_CHR);
print_char_n_times (HORZ_SEP_CH, max_w1);
printf ("%c", BIND_CHR);
print_char_n_times (HORZ_SEP_CH, max_w2);
printf ("%c\n", BIND_CHR);
}
void print_multiplication_row (int m1, int m2, int max_w1, int max_w2) {
printf ("\t%c", VERT_SEP_CH);
int nc = printf ("%c%d%c%c%c%d%c", SPC_CHR, m1, SPC_CHR, MULT_OP_SIGN, SPC_CHR, m2, SPC_CHR);
if (nc < max_w1) {
print_char_n_times (SPC_CHR, max_w1 - nc);
}
printf ("%c", VERT_SEP_CH);
nc = printf ("%c%d%c", SPC_CHR, m1 * m2, SPC_CHR);
if (nc < max_w2) {
print_char_n_times (SPC_CHR, max_w2 - nc);
}
printf ("%c\n", VERT_SEP_CH);
}
void print_multiplication_table (int m1, int m2) {
int col1_max_width = snprintf (NULL, 0, "%c%d%c%c%c%d%c", SPC_CHR, m1, SPC_CHR, MULT_OP_SIGN, SPC_CHR, m2, SPC_CHR);
int col2_max_width = snprintf (NULL, 0, "%c%d%c", SPC_CHR, m1 * m2, SPC_CHR);
for (int i = 0; i < m2; ++i) {
print_row_sep (col1_max_width, col2_max_width);
print_multiplication_row(m1, i + 1, col1_max_width, col2_max_width);
}
print_row_sep (col1_max_width, col2_max_width);
}
int main (void) {
int endTab, selecNum;
print_label();
printf("Enter the table number: ");
scanf("%d", &selecNum);
printf("Enter which number will end in: ");
scanf("%d", &endTab);
print_multiplication_table (selecNum, endTab);
return 0;
}
Output:
% ./a.out
+----------------------+
| multiplication table |
+----------------------+
Enter the table number: 1
Enter which number will end in: 10
+--------+----+
| 1 x 1 | 1 |
+--------+----+
| 1 x 2 | 2 |
+--------+----+
| 1 x 3 | 3 |
+--------+----+
| 1 x 4 | 4 |
+--------+----+
| 1 x 5 | 5 |
+--------+----+
| 1 x 6 | 6 |
+--------+----+
| 1 x 7 | 7 |
+--------+----+
| 1 x 8 | 8 |
+--------+----+
| 1 x 9 | 9 |
+--------+----+
| 1 x 10 | 10 |
+--------+----+
Note that if you want output in the way you have shown, i.e. like this -
+--------+----+
| 1 x 1 | 1 |
+--------+----+
| 2 x 1 | 2 |
+--------+----+
| 3 x 1 | 3 |
+--------+----+
....
....
+--------+----+
| 10 x 1 | 10 |
+--------+----+
then make following change in the statement of for loop of function print_multiplication_table():
print_multiplication_row(i + 1, m1, col1_max_width, col2_max_width);
^^^^^^^^^
arguments swapped
A couple of points:
If you want to maintain the width at the level of numbers printed one down other, in the first column, then calculate the width of maximum digit entered by the user and use it while printing the multiplication row.
Above program is just to show you the way to get the output in desired form. Leaving it up to you to do all sort of optimisations that you can do.
Read about printf() family functions. Read about sprintf(), snprintf() and their return type etc.
This is not the complete solution, but you may be able to work out exactly what you want/need based on the ideas here. (The key ingredient is that log10(), a math library function) will tell how much horizontal space will be needed. Feed it the largest value in each of the 3 numbers columns and you determine the widths needed from that.
#include <stdio.h>
#include <math.h> // for log10()
int demo( int m0, int m1 ) {
char buf[ 100 ]; // adequate
int wid0 = (int)( log10( m0 ) + 1);
int wid1 = (int)( log10( m1 ) + 1);
int widR = (int)( log10( m0 * m1 ) + 1);
int need = 0;
need++; // left 'box'
need++; // space
need += wid0; // first number
need += strlen( " x " ); // mult
need += wid1; // second number
need += strlen( " | " ); // middle box
need += widR; // result
need++; // space
need++; // right 'box'
memset( buf, '\0', sizeof buf ); // start null
memset( buf, '-', need );
puts( buf );
printf( "| %*d x %*d | %*d |\n\n", wid0, m0, wid1, m1, widR, m0 * m1 );
return 0;
}
int main() {
demo( 24, 25 );
demo( 15, 456 );
return 0;
}
Output:
-----------------
| 24 x 25 | 600 |
-------------------
| 15 x 456 | 6840 |
Use the %n directive to gather how many bytes have been printed up to a point and work from there to write your '-' printing loop, for example:
int field_width;
snprintf(NULL, 0, "%d%n\n", 420, &field_width);
char horizontal[field_width + 1];
memset(horizontal, '-', field_width);
horizontal[field_width] = '\0';
Now you can print a horizontal string that's the same width as 420 when printed. Part of your problem is solved by this.
I've adapted my initial example to use snprintf because it occurs to me that you need to work out the column widths from the largest numbers first. In your print loop you'll want to pad out each value to field_width wide; you could use %*d (right justified, space padded) or %-*d (left justified, space padded) or %.*d (zero prefix padded), depending on your choice, for example:
printf("%*d\n", field_width, 1);
... and there's the rest of your problem solved, if I am correct.

value over written in the array during loop

I am currently trying to convert an equation into simpler form and found out that my codes are over writing the value at the end of the loop.
I have found out similar discussions but not exactly what I am looking for. Most of articles were using other languages so I couldn't get the answer.
Any answers are appreciated and thanks in advance.
followings are my code
int index = 0;
int result = 0;
char tresult[100];
char *equation[100] = { NULL, };
char *temp = strtok(input, " ");
for(int i = 1; i < x; i = i + 2)
{
char *temp_sign = equation[i];
if(*temp_sign == '*')
{
result = atoi(equation[i - 1]) * atoi(equation[i +1]);
sprintf(tresult, "%d", result);
equation[i - 1] = tresult;
sprintf(equation[i], "%d", 0);
sprintf(equation[i + 1], "%d", 0);
}
}
for(int j = 0; j < x; j++)
{
printf("%s ", equation[j]);
}
Expected input
5 * 3 + 1 * 2
targeted output
15 0 0 + 2 0 0
I will remove 0 by adding extra codes to make it as
15 + 2
but currently, my output looks like
2 0 0 + 2 0 0
When I print out the value in the loop, all the values were correctly shown. What may be the cause of such problem?
It might be easier to understand if we draw out the pointer instead.
Assuming that input is initially equal to "5 * 3 + 1 * 2", then after the loop equation will look something like this:
+-------------+
| equation[0] | ------------------------\
+-------------+ |
| equation[1] | --> | input[2] | ... | | +------------+-----+
+-------------+ >--> | tresult[0] | ... |
| equation[2] | --> | input[4] | ... | | +------------+-----+
+-------------+ |
| equation[3] | ------------------------/
+-------------+
| equation[4] | --> | input[10] | ... |
+-------------+
| equation[5] | --> | input[12] | ... |
+-------------+
As seen in the above "drawing" both equation[0] and equation[3] will be pointing to the first character of the single array tresult.
And tresult will always contain the contents last written into it with sprintf(tresult, "%d", result). Which in your example will be "2".

Drawing a bar graph in C

The user should input the elements of an array(maximum 20 of them). The task is to draw a bar graph using |, *, and - by using these elements. A line of minuses should be drawn instead of zero, and * instead of last member of an array. If the number is 3 for example, two | and one * above them should be drawn. The problem that I have with my code is that it sometimes takes too long to execute, draws one instead of two minuses between the array elements, and sometimes doesn't draw the line with minuses.
#include <stdio.h>
int main() {
int n[20];
int i,j,counter=0,input=0,min,max;
printf("Elements of the array: \n");
while(input!=1000){
scanf("%d", &input);
n[counter]=input;
counter++;
}
counter--;
min=n[0];
max=n[0];
for(i=1;i<counter;i++){
if(n[i]>max) max=n[i];
if(n[i]<min) min=n[i];
}
for(i=0;i<max-min+1;i++){
for(j=0;j<2*counter;j++){
if(j%2==0 && n[j/2]==max-i) printf("*");
else if(i==max) printf("-");
else if(j%2==0 && n[j/2]>0 && i<max && n[j/2]>max-i) printf("|");
else if(j%2==0 && n[j/2]<0 && i>max && n[j/2]<max-i) printf("|");
else printf(" ");
}
printf("\n");
}
}// Input:4 -3 7 0 -1 1000 Expected output:
*
|
|
* |
| |
| |
| |
---------*-----
| *
|
*
My output:
*
|
|
* |
| |
| |
| |
------*---
| *
|
*
Input: 5 4 3 2 1 2 3 4 5 Expected output:
* *
| * * |
| | * * | |
| | | * * | | |
| | | | * | | | |
---------------------------
My output:
* *
| * * |
| | * * | |
| | | * * | | |
| | | | * | | | | //

Printing two 2D arrays side by side

I've just started doing a unit of programming in C and my first assignment is to make a simple console version of the classic Battleship game.
A part of this - and the part I'm having trouble with at the moment - is displaying information to the player at each turn.
This is what we've been asked to have our display look like:
And, with a minimum of fuss, I've got mine looking like this:
(My Player grid is empty at the moment because its 2D array is empty, but if I use an array with something in it, it's fine.)
My header file:
/* Header files. */
#include <stdio.h>
#include <stdlib.h>
#define UNKNOWN ' '
#define SIZE 10
/* Function prototypes. */
void init(char playerHidden[SIZE][SIZE], char playerReveal[SIZE][SIZE],
char computHidden[SIZE][SIZE], char computReveal[SIZE][SIZE]);
void displayKnownInfo(char playerReveal[SIZE][SIZE],
char playerHidden[SIZE][SIZE],
char computReveal[SIZE][SIZE]);
My C source file:
#include "bship.h"
int main(void)
{
/* Stores player ship position information secret to opponent. */
char playerHidden[SIZE][SIZE];
/* Stores player ship position information known to opponent. */
char playerReveal[SIZE][SIZE];
/* Stores computer ship position information secret to opponent. */
char computHidden[SIZE][SIZE];
/* Stores computer ship position information known to opponent. */
char computReveal[SIZE][SIZE];
init(playerHidden, playerReveal,
computHidden, computReveal);
displayKnownInfo(playerReveal, playerHidden, computReveal);
return EXIT_SUCCESS;
}
/****************************************************************************
* Function init() initialises every cell in the four grids to a safe default
* value. The UNKNOWN constant is used for the initialisation value.
****************************************************************************/
void init(char playerHidden[SIZE][SIZE], char playerReveal[SIZE][SIZE],
char computHidden[SIZE][SIZE], char computReveal[SIZE][SIZE])
{
/*Variables i and j for each dimension of the Arrays*/
int x,y;
/*For each increment BETWEEN 0 and 'SIZE', firstly for i;*/
for(y=0; y<SIZE; y++)
{
/*And then for j;*/
for(x=0; x<SIZE; x++)
{
/*Populate that cell with the constant UNKNOWN*/
playerHidden[x][y]=UNKNOWN;
playerReveal[x][y]=UNKNOWN;
computHidden[x][y]=UNKNOWN;
computReveal[x][y]=UNKNOWN;
}
}
}
/****************************************************************************
* Function displayKnownInfo() presents revealed information about the game in
* the format below. In this example, both contestants have made five
* guesses.
* As you can see, the computer player got lucky with all five guesses and has
* sunk the human players' aircraft carrier. The identity of the ship was
* revealed when the aircraft carrier was HIT the fifth time.
* The human player has been less lucky. The first four guesses were a MISS.
* However, the fifth guess was a HIT on the computer players' submarine. The
* human player does not yet know the identity of this ship yet as it is still
* afloat.
* All other squares are still UNKNOWN.
*
* Player | Computer
* 1 2 3 4 5 6 7 8 9 0 | 1 2 3 4 5 6 7 8 9 0
* +-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+
* a |A| | | | | | | | | | | a | | | | | | | | | | |
* +-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+
* b |A| | | | | | | | | | | b | | | | | | | | | | |
* +-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+
* c |A| | | | | | | | | | | c | | | | | | |=| | | |
* +-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+
* d |A| | | | | | | | | | | d | | |x| | | | | | | |
* +-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+
* e |A| | | | | | | | | | | e | | | | | | | | | | |
* +-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+
* f | | | | | | | | | | | | f | | | | |=| | | | | |
* +-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+
* g | | | | | | | | | | | | g | | | | | | | | | | |
* +-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+
* h | | | | | | | | | | | | h | |=| | | | |=| | | |
* +-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+
* i | | | | | | | | | | | | i | | | | | | | | | | |
* +-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+
* j | | | | | | | | | | | | j | | | | | | | | | | |
* +-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+
* Aircraft Carrier (5/5) | 0/5 ships sunk.
* Battleship (0/4) | 1 hits.
* Destroyer (0/3) | 4 misses.
* Frigate (0/3) |
* Submarine (0/2) |
****************************************************************************/
void displayKnownInfo(char playerReveal[SIZE][SIZE],
char playerHidden[SIZE][SIZE],
char computReveal[SIZE][SIZE])
{
/*Ints for stepping through the arrays*/
int i,j;
/*First row identifier*/
char row='a';
/*Printing first few lines.*/
printf(" Player | Computer\n");
printf(" 1 2 3 4 5 6 7 8 9 0 | 1 2 3 4 5 6 7 8 9 0\n");
printf(" +-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+\n");
printf(" %c |", row);
/*Loop through the arrays*/
for(i=0; i<SIZE; i++)
{
for(j=0; j<SIZE; j++)
{
/*Print the char at [i][j] with a '|' afterwards.*/
printf("%c|",playerReveal[i][j]);
}
/*After reaching column '0' on the display, increment the row identifier*/
row++;
/*And print the 'spacer' row.*/
printf("\n +-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+");
/*If the current row identifier is less than 'k', we want to print it*/
if(row<'k')
{
printf("\n %c |",row);
}
else
{
printf("\n");
}
/*And continue until the array has been printed in full.*/
}
}
}
Eventually, the PlayerHidden array will be overlaid on the PlayerReveal array when a player's ship has been sunk and its identity 'revealed', but for now I'm just wanting to get the computer half of the display working.
Just add this to your code after the second loop where you prints stuff:
printf(" %c |", row);
for(j=0; j<SIZE; j++)
{
/*Print the char at [i][j] with a '|' afterwards.*/
printf("%c|",computReveal[i][j]);
}
So your code looks like:
//...
/*Loop through the arrays*/
for(i=0; i<SIZE; i++)
{
for(j=0; j<SIZE; j++)
{
/*Print the char at [i][j] with a '|' afterwards.*/
printf("%c|",playerReveal[i][j]);
}
printf(" %c |", row);
for(j=0; j<SIZE; j++)
{
/*Print the char at [i][j] with a '|' afterwards.*/
printf("%c|",computReveal[i][j]);
}
//...
Your problem is that you're only printing out the player portion. Take a look at the code:
for(i=0; i<SIZE; i++)
{
for(j=0; j<SIZE; j++)
{
/*Print the char at [i][j] with a '|' afterwards.*/
printf("%c|",playerReveal[i][j]);
}
// ...
}
You need to have another loop where you print out the computerReveal array
for(i=0; i<SIZE; i++)
{
for(j=0; j<SIZE; j++)
{
/*Print the char at [i][j] with a '|' afterwards.*/
printf("%c|",playerReveal[i][j]);
}
for(j=0; j<SIZE; j++)
{
/*Print the char at [i][j] with a '|' afterwards.*/
printf("%c|",computReveal[i][j]);
}
// ...
}
That should do it. You're printing out the full width row separators, but not the portion of the array that creates the cell separators

Double array Strings interconnect in output - C Programming

I have this code:
#include <stdio.h>
int main(void) {
char p[5][5];
int i,j;
for(i=1;i<=1;i++){
for(j=1;j<=2;j++) {
printf("\nInput Product code %d of day %d: ", j,i);
scanf("%s", &p[i][j]);
}
}
for(i=1;i<=1;i++){
for(j=1;j<=2;j++) {
printf("\n\tProduct code %s day %d", &p[i][j],i);
}
}
}
This code outputs:
Input Product code 1 of day 1: hello
Input Product code 2 of day 1: hi
Product code hhi day 1
Product code hi day 1
Does anyone know why hello and hi are interconnecting instead of printing hello in the first one?
I have researched a lot on strings but none seem to work better than this one.
p[][] is not a double array of strings but a double array of chars. It has 5 rows and 5 columns like this:
p[row][column] =
Row| Column -> |
v | 0 | 1 | 2 | 3 | 4 |
| 0 | | | | | |
| 1 | | | | | |
| 2 | | | | | |
| 3 | | | | | |
| 4 | | | | | |
The first scanf() is called when i = 1, j = 1 and copies the string "hello" leaving p[][] like this ('\0' is the NUL character that terminates strings):
| 0 | 1 | 2 | 3 | 4 |
| 0 | | | | | |
| 1 | | H | e | l | l |
| 2 | o |\0 | | | |
| 3 | | | | | |
| 4 | | | | | |
The next time it is called, i = 1, j = 2:
| 0 | 1 | 2 | 3 | 4 |
| 0 | | | | | |
| 1 | | H | h | i |\0 |
| 2 | o |\0 | | | |
| 3 | | | | | |
| 4 | | | | | |
One way you could write this:
#include <stdio.h>
#define MAX_CODE_LEN 80 /* or something */
int main(void)
{
char *code[5][5] = {0},
currentCode[MAX_CODE_LEN] = {0};
int day = 0,
codeNum = 0;
/* start loops at 0 */
for ( day = 0; day < 5; day++ ) {
for ( codeNum = 0; codeNum < 5; codeNum++ ) {
int len = 0;
printf("\nInput Product code %d of day %d: ", codeNum, day);
scanf("%s", currentCode);
/* len doesn't include NUL but malloc needs it */
len = strlen(currentCode);
/* yoda style so compiler catches assignment instead of equality */
if ( 0 == len ) {
/* if the user didn't enter a code move onto the next day */
code[day][codeNum] = NULL;
break;
}
len = len >= MAX_CODE_LEN? MAX_CODE_LEN - 1: len;
code[day][codeNum] = malloc(len * sizeof(char) + 1);
strcpy(code[day][codeNum], currentCode);
}
}
for ( day = 0; day < 5; day++ ) {
for ( codeNum = 0; codeNum < 5; codeNum++ ) {
if ( NULL == code[day][codeNum] ) {
/* no more codes for today */
break;
}
printf("\n\tProduct code %s day %d", code[day][codeNum], day);
}
}
return 0;
}
char p[5][5];
this is a matrix of charachters and not matrix of strings
and with your scanf(), you want to put for each element in the matrix a string. And this is impossible.
You have to use one of the following definition:
1)
char p[5][5][MAX_SIZE_OF_INPUT_STRINGS];
and the scanf should be
scanf("%s", p[i][j]);
2)
char *p[5][5];
and the scanf should be
scanf("%ms", p[i][j]);
p[i][j] here is pointed to a memory allocated dynamically by scanf() and you have to free it with free(p[i][j]) when the p[i][j] become useless in your program
The reason is because strings are just arrays of chars(terminated by \0 or null. Right now, you're indexing chars, and scanf is just taking the char reference you pass it, and filling the rest of the structure with it until it's done filling with the string.
what you're doing is setting p to
* * * * *
* h e l l
o\0 * * *
* * * * *
* * * * *
and then
* * * * *
* h h i\0
o\0 * * *
* * * * *
* * * * *
If I were you, I'd populate closer to something like this
char p[5][6];
int i,j;
for(i=0;i<2;i++)
{
printf("\nInput Product code of day %d: ", i);
scanf("%s", &p[i]);
}
for(i=0;i<2;i++)
{
printf("%s\n", &p[i]);
}

Resources