简体   繁体   English

用 function C 计算数组的长度

[英]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.我的代码有错误,我正在尝试编写一个 function 来计算字符串的字符长度。 I am trying to place the string into an array so that I could use a function to return the length of the string.我正在尝试将字符串放入数组中,以便可以使用 function 来返回字符串的长度。 If the user inputs dad the program prints len of string value: 3 and so on.如果用户输入dad程序打印len of string value: 3等等。 Error error: subscripted value is neither array nor pointer nor vector .错误error: subscripted value is neither array nor pointer nor vector

Function for the length of strings: Function 为字符串的长度:

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

Main function主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;首先将 function 中的计数初始化为 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.其次,字符串计数器 function 中的计数变量仅在字符串计数器 function 的 scope 中,您不能在 main 中访问它,因为在查找全局变量时应谨慎使用。

You are not storing the returned value from function anywhere so store it in some variable.您没有将 function 的返回值存储在任何地方,因此将其存储在某个变量中。 Than try to avoid while(true) as much as you can because you can end in endless loop.尽量避免使用 while(true),因为你可以在无限循环中结束。 Your condition can be your if, so while char is not NULL.你的条件可以是你的 if,所以虽然 char 不是 NULL。

Also with str[1] you are accessing one character, you would need array of pointers for it to be array of strings.同样使用 str[1] 您正在访问一个字符,您需要指针数组才能使其成为字符串数组。 I guess you are just beginning so it's too advanced, you don't need str[1] = text;我猜你才刚刚开始,所以它太高级了,你不需要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[]) .您可以使用int stringcoutner(char *a)int stringcounter(char a[])

I didn't want to write you the solution but I hope it helps a bit.我不想给你写解决方案,但我希望它会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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