find mistakes in following c program

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(){
char str1[] = "abcde";
char str2[] = "012345";
char str3[] = "ABCDEFG";
printf(str1); printf(str2); printf(str3);
Line 8 and 9: Replace sizeof with strlen
Line 10: Replace printf with puts
why ?
what is the reason for replacing ?
Last edited on
sizeof returns a number representing number of bytes. If you want number of elements (I am assuming) then you want to use strlen which will returns a number equivalent to (sizeof str2) / (sizeof *str2) which is the same as number of characters in the string.

But now that I think of it, sizeof char is 1; so I guess your code still works the way you have it, but it is a good idea to know that sizeof does not return number of elements but instead the size in bytes of the variable

As for replacing printf with puts, that was just a way of making each string appear on a new line. So you can ignore it if you want
size of operator when used for arrays gives the size of the array. I think you should get run time error for this code

char str2[] = "012345"; // size 7 bytes, including null char
char str3[] = "ABCDEFG"; // size 8 bytes

strncpy(str2,str3,sizeof(str3)); // this will throw run time error
Last edited on
Topic archived. No new replies allowed.