Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

program to read a char array in c

Tags:

c

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?

like image 284
anothertest Avatar asked Jun 27 '26 05:06

anothertest


2 Answers

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.

like image 161
Some programmer dude Avatar answered Jun 29 '26 22:06

Some programmer dude


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.

like image 30
bfontaine Avatar answered Jun 29 '26 21:06

bfontaine