简体   繁体   English

在C中导航数组的指针问题

[英]Issue with pointers to navigate through arrays in C

I wanted to create a vector (dynamically allocated) where every element of the vector is taken from the command line starting from the 3rd parameter. 我想创建一个向量(动态分配),其中向量的每个元素都从第3个参数开始的命令行中获取。

I wrote this: 我这样写:

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

int main(int argn, char* argc[]) {
    if (argn < 4) {
        printf("Error: invalid parameter number. \n");
        return 0;
    } 
    float min = atof(argc[1]), max = atof(argc[2]), *v, *k;
    int dim = argn-3;
    char **p;
    v = malloc(dim*sizeof(float));
    k = v;
    for (p = argc+3; p < argc+dim; p++) {
        *k = atof(*p);
        k++;
    }
    for (k = v; k < v+dim; k++) {
        printf("%3.f ",*k);
    }
    return 0;
}

The problem is that only the first parameter seems to be taken from the command line, while others not. 问题在于,似乎只有第一个参数是从命令行获取的,而其他则不是。

Example: I launch [ProgramName] 25 30 27 28 29 32 示例:我启动[ProgramName] 25 30 27 28 29 32

It returns me 27.0 0.0 0.0 0.0, but it should return me 27.0 28.0 .29.0 32.0 它返回我27.0 0.0 0.0 0.0,但是应该返回我27.0 28.0 .29.0 32.0

Why isn't my code working? 为什么我的代码不起作用?

Sorry for eventual grammar mistakes, I'm not english. 很抱歉出现语法错误,我不是英语。

You write: 你写:

int dim = argn-3;
...
for (p = argc+3; p < argc+dim; p++) {
...
}

Suppose argn==5 , then dim==2 , and the loop boils down to: 假设argn==5 ,然后dim==2 ,循环归结为:

for (p = argc+3; p < argc+2; p++) {
...
}

which would never run. 永远不会运行。

On a side note, it is customary to use argc and argv as parameters of main. 附带说明一下,习惯上使用argc和argv作为main的参数。 If you follow this, your code will be more readable to others, and others' code will be more readable to you. 如果您遵循此规则,则其他人将更容易阅读您的代码,其他人也将更容易阅读其他人的代码。 Besides, you forgot to print newline. 此外,您忘记了打印换行符。

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

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