I am quite new with C.
#include <string.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char* c=argv[1];
for (int i=0;i<sizeof(c);i++)
{
printf("%c\n",c[i]);
}
return 0;
}
I am trying to write a program to print every character of a word.
When I try with test: It displays t e s t When I try with testtesttest: It displays: t e s t
I don't understand why, can you tell me why please?
Two problems: Using the sizeof operator on a pointer returns the size of the pointer and not what it points to. If you want the length of a string you should use strlen.
The second problem is what will happen if there are no arguments to your program. Then argv[1] will be NULL.
sizeof(c) is the memory size used by c, which is a char*, that is, a pointer on a char. This type takes 4 bytes of memory, hence the t e s t (4 chars). What you want is strlen, which gives you the length of a string.
#include <string.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char* c=argv[1];
int length = strlen(c);
for (int i=0;i<length;i++)
{
printf("%c\n",c[i]);
}
return 0;
}
You should also test that your program gets at least one argument. argc is the length of argv, so you need to ensure that argc > 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With