简体   繁体   English

理解/阐明C语言代码的逻辑

[英]understanding/clarifying logic of code in c

Following is the code from www.tutorialspoint.com, where i am learning basics of algorithm & data structure. 以下是来自www.tutorialspoint.com的代码,我在这里学习算法和数据结构的基础知识。 This tutorial code gives an ex. 本教程代码给出了一个例子。 of insertion operation on array. 数组上的插入操作。

    #include <stdio.h>
    main() {
       int LA[] = {1,3,5,7,8};
       int item = 10, k = 3, n = 5;
       int i = 0, j = n;

       printf("The original array elements are :\n");

       for(i = 0; i<n; i++) {
          printf("LA[%d] = %d \n", i, LA[i]);
       }

       n = n + 1;

       while( j >= k){
          LA[j+1] = LA[j];
          j = j - 1;
       }

       LA[k] = item;

       printf("The array elements after insertion :\n");

       for(i = 0; i<n; i++) {
          printf("LA[%d] = %d \n", i, LA[i]);
       }
    }

I understand the code that it adds new item at give value of k as index of array. 我理解在k的值作为数组索引时添加新项的代码。 And it runs fine without any error when compiled & runs. 并且它在编译和运行时运行良好,没有任何错误。 What confuses me is logic of line LA[j+1] = LA[j] in while loop. 令我困惑的是while循环中线LA[j+1] = LA[j]逻辑。

My understanding is that in c you have to declare the size of array. 我的理解是,在c中,您必须声明数组的大小。 But in ex. 但在前。 code int LA[] = {1,3,5,7,8}; 代码int LA[] = {1,3,5,7,8}; bracket [ ] is empty. 括号[]为空。 So i am not sure if it's a fixed size or more elements can be added to array. 所以我不确定是否是固定大小或可以将更多元素添加到数组。

Now j is given the value of n which is 5(length of array). 现在, jn值为5(数组的长度)。 Array declaration has 5 element, and index of array is 0 to 4. 数组声明有5个元素,数组的索引是0到4。

(On first iteration of while loop)So LA[j + 1] is LA[5 + 1] is LA[6] . (在while循环的第一次迭代中)因此LA[j + 1]LA[5 + 1]LA[6] Now array has only 5 elements indexed 0 to 4. So according to me even after assuming that more element can be added to array, how can it assign value of LA[j] which is 5 to LA[j + 1] . 现在,数组只有5个索引为0到4的元素。因此,即使根据我的假设,即使可以向数组添加更多元素,如何将LA[j]值5分配给LA[j + 1] it's saying LA[6] = LA[5] but there is nothing at index 5 as last index is 4. 就是说LA [6] = LA [5],但索引5却没有,因为最后一个索引是4。

I have tried to search on google but I am not sure what to search except the code or part of code. 我曾尝试在Google上进行搜索,但是除了代码或部分代码外,我不确定要搜索什么。 And searching with code wasn't helpful. 使用代码搜索没有帮助。

Please help me understand. 请帮助我理解。 Thank You. 谢谢。

int LA[] = {1,3,5,7,8};

is equivalent to: 等效于:

int LA[5] = {1,3,5,7,8};

The empty bracket just tells the compiler to automatically set the number of elements as the size of the array. 空括号只是告诉编译器自动将元素数设置为数组的大小。


Yes, you are right, L[6] is out of bounds access, since L has size of 5. So, as you nicely said, the indices are in [0, 4], so L[5] is also out of bounds! 是的,你是正确的, L[6]是出界访问,因为L具有5.大小因此,当你很好地说,该索引是在[0,4],所以L[5]也出界!

This code is wrong! 该代码是错误的!


Read more on Undefined Behaviour : Undefined, unspecified and implementation-defined behavior 阅读有关未定义行为的更多信息: 未定义,未指定和实现定义的行为

First of all it is a very bad code that is written by a very weak programmer and has undefined behaviour. 首先,这是一个非常糟糕的代码,由非常虚弱的程序员编写,并且行为不确定。

For example the array LA 例如数组LA

int LA[] = {1,3,5,7,8};

has only 5 elements. 只有5个元素。

However in these loops 但是在这些循环中

   while( j >= k){
      LA[j+1] = LA[j];
      ^^^^^^^
      j = j - 1;
   }

and

   for(i = 0; i<n; i++) {
              ^^^^ n is already set to 6
      printf("LA[%d] = %d \n", i, LA[i]);
   }

there are attempts to write to the memory beyond the array. 有尝试将数据写入阵列之外的内存。 Also there are some magic values as for example n = 5 . 还有一些魔术值,例如n = 5 It would be much better to write at least 至少写会更好

n = sizeof( LA ) / sizeof( *LA )

Take into account that function main without parameters in C should be declared like 考虑到C中没有参数的main函数应声明为

int main( void )

The program can look for example the following way 该程序可以例如通过以下方式查找

#include <stdio.h>

int main( void ) 
{
    int a[] = { 1, 3, 5, 7, 9 };
    const size_t N = sizeof( a ) / sizeof( *a );

    while ( 1 )
    {
        printf( "The original array elements are:" );
        for ( size_t i = 0; i < N; i++ ) printf( " %d", a[i] );
        printf( "\n" );

        printf( "\nEnter a number to insert in the array (0 - exit): " );
        int value;

        if ( scanf( "%d", &value ) != 1 || value == 0 ) break;

        printf( "Enter a position in the array where to insert: " );
        size_t pos;

        if ( scanf( "%zu", &pos ) != 1 ) break;

        size_t j = N;

        if ( pos < N )
        {
            while ( --j != pos ) a[j] = a[j-1];
            a[j] = value;
        }           

        printf( "\nThe array elements after insertion:");

        for ( size_t i = 0; i < N; i++ ) printf( " %d", a[i] );
        printf( "\n\n" );
    }

    return 0;
}

Its output might look like 它的输出可能看起来像

The original array elements are: 1 3 5 7 9

Enter a number to insert in the array (0 - exit): 2
Enter a position in the array where to insert: 1

The array elements after insertion: 1 2 3 5 7

The original array elements are: 1 2 3 5 7

Enter a number to insert in the array (0 - exit): 6
Enter a position in the array where to insert: 4

The array elements after insertion: 1 2 3 5 6

The original array elements are: 1 2 3 5 6

Enter a number to insert in the array (0 - exit): 0

The logic behind the algorithm is simple. 该算法背后的逻辑很简单。 If you have an array with N elements and want to insert a value in the position pos that less than N then you need to move all elements to the right starting from the position pos and write the new value in the element with index pos . 如果您有一个包含N个元素的数组,并且想要在位置pos中插入一个小于N的值,那么您需要从位置pos开始将所有元素移到右侧,并在索引为pos的元素中写入新值。 The right most element of the original array will be lost because it will be overwritten by the preceding element. 原始数组最右边的元素将丢失,因为它将被前面的元素覆盖。 The program output shows this result. 程序输出显示此结果。

As you correctly pointed out yourself the valid range of indices for the array defined as having 5 elements used in the program is [0, 4] . 正如您正确指出的那样,定义为在程序中使用5元素的数组的有效索引范围是[0, 4]

When an array is declared without its dimension as in this example 如本例所示,在声明数组没有维度时

int a[] = { 1, 3, 5, 7, 9 };

then the compiler determinates its dimension from the number of initializers. 然后,编译器根据初始化程序的数量确定其尺寸。 Thus the above declaration is equivalent to 因此,以上声明等同于

int a[5] = { 1, 3, 5, 7, 9 };

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

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