简体   繁体   English

C编程找到2维数组的长度

[英]C programming find length of 2 Dimensional array

My program grabs command line arguements with argc and argv[]. 我的程序用argc和argv []获取命令行争论。 My question is how can I find the length of argv[1][i]. 我的问题是如何找到argv [1] [i]的长度。

My code that grabs length of argv[] 我的代码抓住了argv []的长度

int my_strlen(char input[]){ 
    int len = 0;
    while(input[len] != '\0'){
       ++len;
    }
    return len;
}

but when I try to find argv[1][len] I get a subscripted value is neither array nor pointer: my attempt 但是当我试图找到argv [1] [len]时,我得到一个下标值既不是数组也不是指针:我的尝试

int my_strlen(char input[]){
   int len = 0;
   while((input[1][len] - '0') != '\0'){
      ++len;
   }
   return len;
}

FULL CODE: 完整代码:

#include <stdio.h>
#include <math.h>

int my_strlen(char input[]);

int main(int argc, char *argv[]){
int length = 0;
length = my_strlen(argv[1]);
long numberArr[length];
int i, j;

for(i = 0; i < length; i++){
  numberArr[i] = argv[1][i] - '0';
}

 return 0;
}

int my_strlen(char input[]){
 int len = 0;
 while((input[1][len] - '0') != '\0'){
  ++len;
 }
 return len;
}

Thanks for any help in advance! 在此先感谢您的帮助!

I think you're confused about the argv content. 我认为你对argv内容感到困惑。 The OS will pass a number of ASCIIZ strings, such that invoking my_program with arguments ala... 操作系统将传递一些ASCIIZ字符串,例如使用参数ala调用my_program ...

my_program first second third

...is similar to having the following declaration in your program... ...类似于在您的程序中声明以下声明...

int argc = 4;
const char* argv[4] = { "my_program", "first", "second", "third" };

Hence, when you index into argv[1][i] you're getting the i-th character in the string "first". 因此,当您索引到argv[1][i]您将获得字符串“first”中的第i个字符。 That's only valid for values of i between 0 (which yields 'f'), and 5 (which indexes to the terminating NUL character '\\0'). 这仅适用于0之间的i(产生'f')和5(它们指向终止NUL字符'\\ 0')的值。

So, there no two-dimensional N*M array, but there is an array of pointers-to-(array-of-char). 所以,没有二维N * M数组,但是有一个指针数组(char-array)。 You can invoke the normal strlen() function as in strlen(argv[1]) to find out the number of characters in each argument. 您可以像在strlen(argv[1])一样调用普通的strlen()函数来查找每个参数中的字符数。 Only argc tells you the total number of elements in argv . 只有argc告诉你argv的元素总数。

Does that help? 这有帮助吗?

In main , you're passing argv[1] to my_strlen . main ,您将argv[1]传递给my_strlen That means my_strlen just receives a normal, single-dimension string. 这意味着my_strlen只接收一个普通的单维字符串。 It doesn't need to do input[1][len] , just input[len] . 它不需要input[1][len] ,只需input[len]

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

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