-4

So basically according to definition of array we cannot change array size. But if I am adding element to a same array by shifting other elements to the right of array, so the array size is going to increase.

How this is possible?

#include<stdio.h>

int main() {
  int n, j, k, item;
  printf("Enter size of array:\n");
  scanf("%d", &n);
  printf("Enter element to insert and position of element:\n");
  scanf("%d,%d", &item, &k);
  int a[n];
  for (j = 0; j < n; j++) {
    printf("Enter a[%d] element:\n", j);
    scanf("%d", &a[j]);
  }
  j = n - 1;
  while (j >= k - 1) {
    a[j + 1] = a[j];
    j = j - 1;
  }
  a[k - 1] = item;
  for (j = 0; j <= n; j++) {
    printf("%d\n", a[j]);

  }
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
ALMAS SANGLE
  • 23
  • 1
  • 7
  • 2
    This is possible because of copy paste. :) You copy the whole array to a new location and redefine it there with extra size. :D – Ahtisham Jan 29 '19 at 15:39
  • 3
    Your description is unclear. Please [edit] your question and show us a small code example what you mean. – user694733 Jan 29 '19 at 15:39
  • 3
    It isn't possible. Writing outside the array has undefined behaviour so it may appear to work, but it doesn't. – molbdnilo Jan 29 '19 at 15:41
  • If you shift elements to the right of the array, then you will push them outside of the array and this will make your program erroneous. – machine_1 Jan 29 '19 at 15:42
  • @molbdnilo You can define a new location that is possible to accommodate the new size of array and then copy all the values from the previous location to new. That is what `realloc()` does I guess. – Ahtisham Jan 29 '19 at 15:45
  • 1
    @Ahtisham true that, but that's not "changing the size of the array", so molbdnilo is right. – Blaze Jan 29 '19 at 15:47
  • @Ahtisham Pointing to the first element of a different array is not the same thing as expanding an array. – molbdnilo Jan 29 '19 at 15:49
  • There's a reason why linked lists were invented. – Lundin Jan 29 '19 at 15:49
  • Once an array is defined, its size cannot change - neither larger nor smaller. To add beyond an array's range, do not use arrays - Code needs a new approach. – chux - Reinstate Monica Jan 29 '19 at 16:09

4 Answers4

2

Shifting the contents of the array to the right will not resize the array. If the array was not already large enough to hold the result of the shift, then you have overrun the array object, and have induced undefined behavior.

There is no way to dynamically increase the size of a variable with static or auto duration (e.g., global or local variables), and this includes arrays. If your compiler supports variable length arrays (VLAs), changing the value of the expression controlling the dimension of the array does not affect the array's size.

int main (void) {
    int n = 3;
    int v[n];
    printf("%zu\n", sizeof(v));
    ++n;
    printf("%zu\n", sizeof(v));
}

The program above will print the same value twice.

jxh
  • 69,070
  • 8
  • 110
  • 193
  • please take a look on my code. It is not throwing any error and giving a correct output. – ALMAS SANGLE Jan 29 '19 at 16:30
  • @ALMASSANGLE: One of the effects of undefined behavior is working as expected - you may be indexing into memory that isn't "important", but you're still accessing memory outside the array bounds. – John Bode Jan 29 '19 at 16:52
  • @ALMASSANGLE: https://tio.run/##dY5NTsMwEIX3PsWjKD8mCSKl6qIu5SBuFpbdgpN2XDWBDeLsYZwI1A22pfHMmzfz2erN2vHekz19uAO2/eB8eHzfCeFpwNl4Qv4ZvJP4GmOFSvjhcC7RKdFbQ8d8kThMb1EiZTmd9bSTapoRwqXXd1TUzZwbTfx7iGW8oKqVOIYr8ih5LjwpDluQQlF4KcDnb0/cYLRv5I2nZQ83t9gxEqqqnT1Gtw0rHKq42OguphFNicuVjTwwImwYfE88eAKS/8AU9Q3Orz1xiWVjBCrZEvskXpHx3SDbUybV@D2usMZS1FjiGasf – jxh Jan 29 '19 at 18:06
  • @jxh that's what i am asking. According to definition of array, array size is not supposed to resize but in this case when we are inserting an element the size is changing bcoz the array is accessing element from the memory location which is outside the array. So how is it possible?? – ALMAS SANGLE Jan 29 '19 at 18:57
  • 1
    C allows you to author incorrect code. Note the `oops` in my link. You think just because the program displayed the array contents you expected the program is ok. That's incorrect. – jxh Jan 29 '19 at 19:00
0

I am not entirely sure what you're asking, but for any readers interested in knowing how to dynamically change the size of an array in C: if an array is declared in stack memory, its size cannot change. However, a block of memory intended to be used as an array is declared on the heap (i.e. with malloc or calloc), can be reallocated with a different size if necessary:

int *data = malloc(10 * sizeof(int)), *data2 = NULL;
int i;
if(data == NULL)
{
     perror("malloc");
     exit(EXIT_FAILURE);
}
for (i = 0; i < 10; i++)
{
    data[i] = i;
}

data2 = realloc(data, 11 * sizeof(int));
if(data2 == NULL)
{
     free(data);
     perror("realloc");
     exit(EXIT_FAILURE);
}
else 
{ 
    data = data2; 
}
data[10] = 10;

for (i = 0; i < 11; i++)
    printf("%d ", data[i]);

free(data);
data = NULL;

Shifting elements in an array down one element will not change its size.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
0

If you declare an array as

T a[N]; // assume N is a constant expression

then a can only ever hold N elements of type T - no more, no less. You cannot add extra elements to the array, nor can you remove elements from the array.

However...

C does not force any bounds checking on array subscripting, so it's possible that you can read or write past the end of the array such as

a[N + 2] = x;

The behavior on doing so is undefined - your program may work as expected, or it may crash immediately, or you may corrupt other objects in the program. The runtime environment will (most likely) not throw an IndexOutOfBounds-type exception.

There is a thing called a variable-length array that was added in C99, where the array size is not a constant expression:

size_t size = some_value();
T a[size];

Variable length arrays are only variable length in the sense that their size isn't determined until runtime - however, once defined, their size is fixed throughout their lifetime, and like regular arrays, they cannot grow as new items are added.

If you dynamically allocate a chunk of memory using

T *a = malloc( sizeof *a * some_size );

then you can grow or shrink that chunk of memory using realloc:

T *tmp = realloc( a, sizeof *a * (some_size * 2) ); 
if ( tmp )
{
  a = tmp;
  some_size *= 2;
}
John Bode
  • 119,563
  • 19
  • 122
  • 198
0

.... array we cannot change .. But if I (do something special) ... the array size is going to increase.

How this is possible?

Undefined behavior

Arrays cannot change size once defined.

Code attempts to assign a[j + 1] with j = n-1 and that is a[n]. This is outside array a[] and so undefined behavior. Rest of code is irrelevant for at that point anything is possible, code crash, error report, even apparent successful array expansion, etc.

  int a[n];
  ...
  j = n - 1;
  while (j >= k - 1) {
    a[j + 1] = a[j]; // To attempt access to `a[n]` is UB
Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • Code is not giving any error. It is giving a correct output. I am working on ubuntu. – ALMAS SANGLE Jan 29 '19 at 16:40
  • @ALMASSANGLE C does is not required to provide an error message. Code remains flawed - even if today you do not notice any problem. If one cheats on an exam, it is still cheating, even if one is not caught. Do not expect C to emit code to check that source code did not cheat - that bloats and slows run-time performance. If you need to be informed when code attempts something it should not, consider another language. – chux - Reinstate Monica Jan 29 '19 at 16:44