2

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?

2
  • 2
    sizeof(c) gives the size of a char* and not the length of the string Commented Jul 12, 2014 at 14:37
  • 2
    sizeof(c) returns the size of a pointer on your machine Commented Jul 12, 2014 at 14:37

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

3

sizeof operator returns the size of the type of operand. c is of type char *, therefore sizeof(c) will return the size of char * instead of the string. You should use strlen(c).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.