Menu
CoddyTech

Growing Without Losing Data

Lesson 34 of 48 in Coddy's C for C# Developers course.

C# Array.Resize replaces the array reference when size changes; other references may still see the old managed array. C realloc may free or move the original storage, making aliases invalid after success.

realloc can move storage. Preserve the original pointer until success; aliases may become invalid after a successful call.

C# example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
class Program {

static void Main(){
int[] a={2,4};Array.Resize(ref a,3);a[2]=6;Console.WriteLine(a[2]);
}
}

C# output:

6

C example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>

int main(void) {
int *values=malloc(2*sizeof *values);if(!values)return 1;values[0]=2;values[1]=4;int *grown=realloc(values,3*sizeof *values);if(!grown){free(values);return 1;}values=grown;values[2]=6;printf("%d\n",values[2]);free(values);
return 0;
}

C output:

6
challenge icon

Challenge

Easy

First input integer is the new value; remaining up to 16 integers are the existing sequence. append_value(data,count,value) appends if count is below 16. On capacity rejection or allocation failure return false and preserve pointer, count and contents. On success transfer the grown allocation through *data and increment *count. Driver verifies old elements and prints count:last, or full:count.

Edit the unlocked source and header files. Keep the declared public API compatible with the visible locked main.c, which calls it directly. Do not add another main. All numeric task fixtures are small enough to avoid overflow unless the task explicitly checks a range. Print only the specified output; the driver supplies input parsing and output when shown.

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int value;if(scanf("%d",&value)!=1)return 1;int old[16];size_t n=0;while(n<16 && scanf("%d",&old[n])==1)n++;int *data=n?malloc(n*sizeof *data):NULL;if(n && !data)return 2;if(n)memcpy(data,old,n*sizeof *data);int *before=data;size_t original=n;bool ok=append_value(&data,&n,value);if(ok){if(n!=original+1 || (original && memcmp(data,old,original*sizeof *data)!=0)){free(data);return 3;}printf("%zu:%d\n",n,data[n-1]);}else{if(data!=before || n!=original || (n && memcmp(data,old,n*sizeof *data)!=0)){free(data);return 3;}printf("full:%zu\n",n);}free(data);return 0;}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C for C# Developers

Practice on your own: Online C compiler