Markovnikov
Markovnikov

Reputation: 41

C: Program that prints a certain number of characters only

I am working on a program that, when specified by a number entered by the user, will only print out that number of characters. For example, if the user enters the number 10, then if 14 characters are entered (including newlines, blanks and tabs) only 10 characters will be printed. My code seems to work for the first three or so characters, then it prints out garbage. I'm not sure what is wrong.

#include <stdio.h>
#include <stdlib.h>

void findchars(char *abc, int number);

int main(void)
{
    char *array; // the actual array 
    int num; // number of characters to read, becomes array value

    printf("Number of characters:");
    scanf_s("%d", &num);

    array = (char *)malloc(num * sizeof(char));

    findchars(array, num);

    printf("The first %d characters: ", num);

    puts(array);

    free(array);

    return 0;
}

void findchars(char *abc, int number)
{

    int i; 

    printf("Type characters and I will stop at %d: ", number);

    for (i = 0; i < number; i++)
    {
        abc[i] = getchar();
    }

}

Upvotes: 0

Views: 1151

Answers (1)

aragaer
aragaer

Reputation: 17848

You are passing non-zero-terminated array to puts. If you want your program to work just create your array 1 item bigger and add '\0' in the end.

Edit: like this

array = (char *)malloc((num+1) * sizeof(char));

and then right before puts:

array[num] = '\0'; 

Upvotes: 2

Related Questions