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'){
    – BLUEPIXY
    Oct 14, 2015 at 0:52
  • or char dog[] = {"dog"}; ..int countArrayChars(char strArray[]){
    – BLUEPIXY
    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. Oct 14, 2015 at 0:59
  • Can you give a quick/simple explanation of why having two [ ] [ ] fixed it? Sorry, sort of a beginner.
    – Boris R
    Oct 14, 2015 at 1:13
  • Nvm, multidimensional array
    – Boris R
    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";
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
  • Sorry to disagree, it compiles and runs and gives 3.
    – BobRun
    Oct 14, 2015 at 2:15
  • Could you try a C compiler ? That's what I am using, not C++
    – BobRun
    Oct 14, 2015 at 2:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.