Handling of Array in C and C#

multidimensional array in c#
jagged array in c#
dynamic array in c#
array c#
c# array methods
array of objects c#
string array in c#
c# array add

I tried to insert an element in an array and it failed with array index out of bounds

I tried in C# it failed it works fine in c

int[] LA = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;   
n = n + 1;
while( j >= k) 
    LA[j+1] = LA[j];
    j = j - 1;
LA[k] = item;

but it works in c

int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
n = n + 1;
while( j >= k) {
    printf("j+1 =%d",j+1);
    LA[j+1] = LA[j];
    j = j - 1;

Can someone please explain why this is? and what about other languages will it keep varying? Thanks.

Many answers say it doesn't work in c so i have uploaded an image ]1

Oh no, this doesn't "work", that looks like pretty blatant out of bounds writing, and thus you're getting undefined behavior. You cannot dynamically grow an array in C, they are statically sized at the point of "creation".

Note that C doesn't say that doing undefined things will result in any particular measurable result[*], so it can appear to do the intended thing, but still be completely broken.

[*]: That is what "undefined" means: there is no definition of what is going to happen. Some people seem to interpret it as "we're going to get the error handler for triggering that thing they call 'undefined behavior'", but that is not true. Anything could happen, anything.

C#, Since arrays are objects in C#, we can find their length using member length. This is different from C/C++ where we find length using sizeof operator. A C# array� You can copy an array variable into another target array variable. In such case, both the target and source point to the same memory location − int [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks; When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type.

On the first iteration of the loop, j = n = 5. However you're reading from LA[j], which is LA[5]. LA only 5 elements, so you can read from and write to LA[0] to LA[4]. You're then trying to write to LA[6], which is even further beyond the bounds of the array!

Fix your algorithm - you're not allowed to read from or write to elements outside of the bounds of the array.

The reason this "works" in C is that C isn't checking whether you're reading or writing outside of the bounds of the array. You're actually reading some random value that's sitting in memory beyond the end of your array. Technically this is invoking undefined behaviour, and anything at all could happen.

Arrays, Oh no, this doesn't "work", that looks like pretty blatant out of bounds writing, and thus you're getting undefined behavior. You cannot� C# Exception Handling - Tutorial to learn Exception Handling in C# in simple, easy and step by step way with syntax, examples and notes. Covers topics like try block, catch block, finally block, Using multiple catch Clauses, Nested try block, Custom exception class, etc.

Instead of array you can insert item easily using C# ArrayList or List like:

 static void Main(string[] args)
     ArrayList LA = new ArrayList() { 1, 3, 5, 7, 8 };
     Console.WriteLine("The Original array elements are:" + string.Join(",", LA.ToArray()));

     int item = 10, k = 3;
     LA.Insert(k, item);
     Console.WriteLine("The array elements after insertion:" + string.Join(",", LA.ToArray()));


Dotnetfiddle : https://dotnetfiddle.net/ISzZPz

C# - Arrays, Similarly, we can define arrays of any type such as double, character, and string. In C#, arrays are objects. That means that declaring an array� Arrays are zero indexed: an array with n elements is indexed from 0 to n-1. Array elements can be of any type, including an array type. Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable<T>, you can use foreach iteration on all arrays in C#. Related sections. Arrays

Handling of Array in C and C#, Learn about multidimensional and jagged array next. Frequently Asked Questions. How to search in array in C#? � How to sort an array in C#?� You can initialize an array in C either one by one or using a single statement as follows − double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].

Working With C# Arrays, In this part of the C# programming tutorial, we will cover arrays. We will initiate arrays and read data from them. C# array definition. An array is a� In C#, System.IO namespace contains classes which handle input and output streams and provide information about file and directory structure. File-Handling-Class-Hierarchy Here we are going to discuss about two classes which are useful for writing in and reading from the text file.

C# Arrays (With Easy Examples), C# Array Examples. Arrays are using for store similar data types grouping as a single unit. We can access Array elements by its numeric index. The array� Write a C program to convert uppercase to lowercase character and vice versa in a text file. Write a C program to find properties of a file using stat() function. Write a C program to check if a file or directory exists. Write a C program to rename a file using rename() function. Write a C program to list all files and sub-directories recursively.

  • @DmitryBychenko in this case, the error is that he's reading from LA[6], so using a List<T> won't help.
  • btw: I can "fix" the C# too, look! int* LA = stackalloc int[] { 1, 3, 5, 7, 8 }; - done! this will also "work" for the same reasons (meaning: it is equally broken) - the reasons here being: your C array isn't bound-checked (just like my C# pointer); you have then accessed memory past the end of the defined range - that might be unused memory, it could be something really important, it could be an invalid page; at that point: your code is just broken
  • C# has fewer nasal demons. This is something that makes C# easier; you get an error message now rather than a really hard to find bug weeks later.
  • @nevas C arrays (which, when indexed into, are essentially the same as pointer expressions) are indeed not bounds checked; this is a feature of the language and that concept; if you want a bounds-checked type : don't use raw arrays (/pointers)
  • @nevas: Array accesses in C are not bounds checked. Attempting to access an array element outside the range of the array leads to undefined behavior, meaning there’s no requirement on the compiler or runtime environment to do anything in particular. Your code may appear to work as intended, or it may corrupt other data, or it may crash outright.
  • "Anything could happen, anything". Undefined does not mean anything can happen. There are a set of things that could possibly happen when you read outside the bounds of an array. Your computer turning into a rabbit is not one of them. :)
  • @MineR This is writing, not reading. Also, of course the computer can't start violating laws of physics all of a sudden, but the point is that the C standard doesn't limit what could happen. You can't reason about it, unless you know what code the compiler happened to generate for this case, and how the underlying machine acts when the actual instructions generated execute under these conditions.
  • OR WORSE. U.B. means that it can work fine during decades and then fail, without any apparent reason.
  • Please don't use ArrayList - it was outdated in C# 2, 13 years ago! Use a generic List<T>. Also note that your suggestion combined with his code still crashes.
  • No. It doesn't crashes. I execute it in a console application and pest it here.
  • As in, if you try and use the OP's original algorithm - LA[j+1] = LA[j]; etc - that will crash, because you're still doing an out-of-bounds array read. Your answer ignores this, by throwing away the OP's original algorithm and writing something else instead.
  • Very funny argument :) why you want to use LA[j+1] = LA[j]; with ArrayList. ArrayList has its own function for insertion. Anyway my focus is on the solution of this problem using C# not the output. Because you can represent this output in too many ways in C#.
  • @canton7 Other thing is, why you discourage someone using ArrayList. According to the problem domain, if somebody needs using multiple type together like string and int, in that case he has to be use ArrayList. Because you can't use multiple type using List.