Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Array Not Printing with Printf

array printing

  • Please log in to reply
No replies to this topic

#1 Wolvendeer


    CC Lurker

  • New Member
  • Pip
  • 3 posts

Posted 05 March 2012 - 04:13 AM

I decided that I wanted to learn C, so I went out and got a copy of K&R. I'm having a problem with one of the exercises. With the below program, it will count the length of the string you input, but it won't print the string back out, it will just print a blank space, so the output looks something like the below. I heard that making the array static could fix it, so I tried, but it didn't change anything.

(Output): (60 character wide blank space) 6

/* Title: Exercise_1_16
** Description: A program that prints the length of strings and as much text as the buffer will allow.*/

#include <stdio.h>

#define ARRAY_SIZE 1024

int mygetline(char *line_input, int buffer_size);

main() {
	int strlen;
	char line[ARRAY_SIZE];

	while ((strlen = mygetline(line, ARRAY_SIZE)) > 0) {
		printf("%60s\t%d\n", line, strlen);

int mygetline(char *line_input, int buffer_size) {
	int c, i;

	for (i = 1; i < buffer_size && (c = getchar()) != EOF && c != '\n'; i++) {
		line_input[i] = c;

	if (c == '\n') {
		line_input[i] = c;
	line_input[i] = '\0';
	return i;

Edit - I went through my code a few more times, and I found that it was an off by one error. Because the for loop in the mygetline function was starting at i=1, it was printing at [1] in the array and leaving a \0 at position [0].

Edited by Wolvendeer, 05 March 2012 - 12:50 PM.

  • 0

Also tagged with one or more of these keywords: array, printing

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download