简体   繁体   中英

Counting the length of an array with a function C

I have an error with my code, I am trying to write a function that counts the length of characters of a string. I am trying to place the string into an array so that I could use a function to return the length of the string. If the user inputs dad the program prints len of string value: 3 and so on. Error error: subscripted value is neither array nor pointer nor vector .

Function for the length of strings:

int stringcounter(a){
    int count;
    while (true){
        if (a[count] != NULL){
            ++count;
        }
        else{break;}
    }
    return count;
}

Main function

int main(void) {
    char text[100];  //string
    char str[100]={0};  // storing the text string
    printf("Enter an interesting string of less than %d characters:\n", 100);
    scanf("%s",text);
    str[1] = text; 
    stringcounter(str);

    printf("len of string value: %d", count);
    return 0;
}

There are many mistakes. First initialise count in function to 0: int count = 0; because it is set to any value if you don't init it. Secondly, count variable in stringcounter function is only in scope of stringcounter function you can't access it in main, for that look up global variables but they should be used rarely and with caution.

You are not storing the returned value from function anywhere so store it in some variable. Than try to avoid while(true) as much as you can because you can end in endless loop. Your condition can be your if, so while char is not NULL.

Also with str[1] you are accessing one character, you would need array of pointers for it to be array of strings. I guess you are just beginning so it's too advanced, you don't need str[1] = text; at all. You can just init string for example as you did with text, take input in it, than send it in a funciton, calc the length and return it in some variable. There is no need for second string variable. And yeah, you need to declare the parameter type. You can use either int stringcoutner(char *a) or int stringcounter(char a[]) .

I didn't want to write you the solution but I hope it helps a bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM