简体   繁体   中英

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

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM