Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C programming beginner - Please explain this error

Tags:

arrays

c

I'm just starting off with C and was trying out a few examples from Ritchie's book. I wrote a small program to understand character arrays, but stumbled on some errors, and was hoping for some insight on what I've understood wrong:

#include <stdio.h>
#define ARRAYSIZE 50
#include <string.h>

main () {
  int c,i;
  char letter[ARRAYSIZE];
  i=0;
  while ((c=getchar()) != EOF )
  {    
    letter[i]=c;
    i++;
  }
  letter[i]='\0';
  printf("You entered %d characters\n",i);
  printf("The word is ");

  printf("%s\n",letter);
  printf("The length of string is %d",strlen(letter));
  printf("Splitting the string into chars..\n");
  int j=0;
  for (j=0;j++;(j<=strlen(letter)))
    printf("The letter is %d\n",letter[j]);
}

The output is:

$ ./a.out 
hello how are youYou entered 17 characters
The word is hello how are you
The length of string is 17Splitting the string into chars..

What is happening? Why isn't the for loop giving any output?

like image 867
Joel G Mathew Avatar asked May 09 '12 17:05

Joel G Mathew


People also ask

What are the 3 types of programming errors?

When developing programs there are three types of error that can occur: syntax errors. logic errors. runtime errors.

What is a logic error in C?

(c) Logic errors A logic error (or logical error) is a 'bug' or mistake in a program's source code that results in incorrect or unexpected behaviour. It is a type of runtime error that may simply produce the wrong output or may cause a program to crash while running.


3 Answers

The syntax should be;

for (j=0; j<strlen(letter); j++)

Since strlen is costy operation, and you don't modify the string inside the loop, it's better to write like:

const int len = strlen(letter);
for (j=0; j<=len; j++)

Besides, it's strongly recommanded to always check for buffer overflow when working with C-strings and user-input:

while ((c=getchar()) != EOF && i < ARRAYSIZE - 1)
like image 67
aland Avatar answered Sep 22 '22 07:09

aland


The error is in the for, simply swap the ending condition and the increment like this:

for (j = 0; j <= strlen(letter); j++)

Question: what's that last character?

like image 37
BlackBear Avatar answered Sep 20 '22 07:09

BlackBear


for (j=0;j++;(j<=strlen(letter))) it's not correct.

It should be for (j=0; j<=strlen(letter); j++) - increment at the third position.

like image 35
Luka Ramishvili Avatar answered Sep 20 '22 07:09

Luka Ramishvili