0

I want to get the elements of an array of characters, but no success at all, the problem is that I only get the first and last element and nothing more, my code is:

void getcharacters(char *cad)
{
 int l;
 int *i;
 l=strlen(cad);
 for (i=&cad[0];i<&cad[l];i++){
     printf("%c\n",*cad);
 }
}

any help? Thanks

3
  • 3
    Shouldn't i be declared as char *i? Commented Dec 13, 2012 at 3:40
  • Also, why print *cad? It never changes from the first character. Commented Dec 13, 2012 at 3:41
  • Perhaps you intended to print *i instead of *cad? Commented Dec 13, 2012 at 3:41

4 Answers 4

4

The size of an int can be as big as 4 x the size of a char, so when you do i++ you are actually skipping 3 chars.

Also, you print out *cad instead of *i.

To fix change i to char* and print *i instead of *cad

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

2 Comments

"int can be as big as 4 chars" lol, I would say char is not guaranteed to be the same size of int (and in most cases they will never be)
@AlvinWong typically sizeof(int) == 4 while sizeof(char) == 1 i believe
2

You are using the same character (*cad or cad[0]) for all printf's. What you need is to use the index to get the next char in each iteration. Also i needs to be a pointer to char:

void getcharacters(char *cad)
{
 int l;
 char *i;
 l=strlen(cad);
 for (i=&cad[0];i<&cad[l];i++){
     printf("%c\n", *i );
 }
}

Comments

2

Why don't you iterate from first character to the last one and accessing them as array index

int i;
int l=strlen(cad);
for (i=0;i<l;i++)
{
  printf("%c\n",cad[i]);
}

Comments

1

Other answers have told you why it plain doesn't work, I'm wonder why you're not just iterating until the null terminator?

void getcharacters(char *cad)
{
 char *i;
 for (i = cad; *i; i++) {
     printf("%c\n",*i);
 }
}

1 Comment

i should be a *char instead of *int

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.