简体   繁体   English

如何将数组中的第一个元素分配给变量?

[英]How to assign first element in array to a variable?

I'm new to c and I have trouble with arrays in c. 我是c的新手,并且在c中遇到数组问题。 I don't know how to assign first element from an array to an int variable. 我不知道如何将数组中的第一个元素分配给一个int变量。 When I tried, I got a random large integer from nowhere even index was in range. 当我尝试时,我什至没有索引就在范围内得到一个随机的大整数。

This is part of my code: 这是我的代码的一部分:

int solve(int *elev, int n)
{
    for (int i = 0; i < n; ++i)
        printf("%d ", elev[i]);
    putchar('\n');

    printf("%d %d %d %d %d\n", elev[0], elev[1], elev[2], elev[3], elev[4]);

    int low = elev[0];
    int high = elev[4];

    printf("low:%d high:%d\n");

    // ...
}

Partial output: 部分输出:

1 4 20 21 24
1 4 20 21 24
low: 362452 high: 7897346

What was a cause of above output? 是什么原因造成了上述产出的增加?

It looks like you're not passing the low or high variables as arguments to the printf() call, on this line: 看来您没有在这一行上将lowhigh变量作为参数传递给printf()调用:

printf("low:%d high:%d\\n")

If you provide the low and high variables as arguments to printf() then the expected output should be printed to the console, like so: 如果提供low变量和high变量作为printf()参数,则应将预期输出打印到控制台,如下所示:

printf("low:%d high:%d\n", low, high);

The "print format" of "low:%d high:%d\\n" being passed to the printf() function states that number values will be displayed for each occurrence of %d in the format string. 传递给printf()函数的"low:%d high:%d\\n"的“打印格式”指出,在格式字符串中每次出现%d都会显示数字值。

In order to specify the actual values that will be displayed for each occurrence of %d , additional arguments must be provided to the printf() function - one for each occurrence of %d : 为了指定将在每次出现%d显示的实际值,必须向printf()函数提供其他参数-对于每次出现%d

printf("low:%d high:%d\n", 
low, /* <- the value of low will be printed after "low:" in output the string */
high /* <- the value of low will be printed after "low:" in output the string */
);

If these additional arguments are not provided, the program will still compile and run however, at run-time, the program will basically display what ever value is found at the memory locations where it expected to find values for each of the %d occurrences. 如果未提供这些附加参数,则程序仍将编译并运行,但是,在运行时,程序将基本上显示在内存位置找到的任何值,希望在内存位置找到每个%d事件的值。

For more information on printf() , you might like to see this documentation - hope this helps! 有关printf()更多信息,您可能希望查看本文档 -希望有所帮助!

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

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