1
#include <stdio.h>
#include <stdlib.h>


int countArrayChars(char *strArray[]){
    int i=0;
    while (strArray[i] != '\0'){
        i++;
    }
    printf("%d\n", i);
    return i;
}

int main(int argc, const char * argv[]) {
    char *dog[] = {"dog"};
    countArrayChars(dog);

For some reason, it prints "5".

Shouldn't it print 3? I even tried to put \0 after the "g".

5
  • --> while (strArray[0][i] != '\0'){ Commented Oct 14, 2015 at 0:52
  • or char dog[] = {"dog"}; ..int countArrayChars(char strArray[]){ Commented Oct 14, 2015 at 0:58
  • 1
    Like BLUEPIXY said, strArray is an array of strings so strArray[0] is a pointer to the first string in the array and strArray[1] doesn't exist. What you are iterating is the bytes in the address of the pointer to the string. Commented Oct 14, 2015 at 0:59
  • Can you give a quick/simple explanation of why having two [ ] [ ] fixed it? Sorry, sort of a beginner. Commented Oct 14, 2015 at 1:13
  • Nvm, multidimensional array Commented Oct 14, 2015 at 1:43

2 Answers 2

1

You declare array of string and initialize it with dog.

char *dog[] = {"dog"};

Actually it represented as

dog[0] = "Dog";     //In your case only element index with 0.
...............
...............
dog[n] = "tiger";   //If there Have n+1 element

Hence your array size is 1. Which hold constant string dog. To access it you should use dog[0].

So without less modification you can use your code as:

int countArrayChars(char *strArray[])
{
    int i=0;
    while (strArray[0][i] != '\0')
    {
        i++;
    }
    printf("%d\n", i);
    return i;
}

int main(int argc, const char * argv[])
{
    char *dog[] = {"dog"};
    countArrayChars(dog);
}

Or if you want to declare a string use

char *dog = "dog";

or

char dog[] = "dog";
Sign up to request clarification or add additional context in comments.

Comments

0

Please try this

 #include <stdio.h>
 #include <stdlib.h>


int countArrayChars(char *strArray){
    int i=0;
    while (strArray[i] != '\0'){
        i++;
    }
    printf("%d\n", i);
    return i;
}

int main(int argc, const char * argv[]) {
    char *dog[] = "dog";
    countArrayChars(dog);
    }

2 Comments

Sorry to disagree, it compiles and runs and gives 3.
Could you try a C compiler ? That's what I am using, not C++

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.