1
# include <stdio.h>
# include <stdlib.h>
#include <string.h>
void main (void)

{
int size, i,j;
printf("enter no. of employee\n");
scanf("%d", &j);
printf("size of employee id\n");
scanf("%d",&size);
char *m[j];
for (i=0; i<j;i++) {
m[i] = (char*) malloc(size*sizeof(char));
}

for (i=0; i<j;i++) {
printf("Enter employee id of %d\n ",i+1);
getchar();
gets(m[i]);
}
printf("employee id are\n ");
for (i=0; i<j;i++){
puts(m[i]);
}
}

i made a programme that would dynamically take input from user about no. of employee and their id size then print it however my output lack first character every time when printing and i haven't been able to spot the error

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
vatsal
  • 11
  • 6
  • 1
    You probably want a single `getchar();` after the last `scanf`, but you don't want it in the loop. You should read [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) as well. – Retired Ninja May 07 '23 at 19:25
  • 1
    `m[i] = (char*) malloc(size*sizeof(char));` hasn't allowed for the string terminator. Add 1: `m[i] = malloc(size + 1);`. I also [removed the cast](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc), and `char` has size 1 by definition. – Weather Vane May 07 '23 at 19:27
  • Having said that, there is no protection at all against incorrect (or malicious) entries as Ninja wrote. And code freely mixing `scanf()` with `getchar()` and `fgets()` is likely to be problematical unless you are 100% familar with their differences and quirks. – Weather Vane May 07 '23 at 19:30

1 Answers1

2

For starters according to the C Standard the function main without parameters shall; be declared like

int main( void )

The function gets is unsafe and is not supported by the C Standard, Instead use standard C function either scanf or fgets.

As for your problem then the first character is lost due to this call

getchar();

within the for loop.

You could write instead.

while ( getchar() != '\n' );
for ( i = 0; i < j; i++ ) 
{
    printf("Enter employee id of %d\n ",i+1);
    fgets( m[i], size, stdon );
    m[i][ strcspn( m[i], "\n" ) ] = '\0';
}

And you should free all the allocated memory before exiting the program

for ( i = 0; i < j; i++ )
{
    free( m[i] );
}

Also the program will be much more safer if you will check the result if these calls of scanf

scanf("%d", &j);

and

scanf("%d",&size);

at least that the entered values are greater than 0.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335