开发者

Array Related Question

开发者 https://www.devze.com 2023-01-03 12:55 出处:网络
I have the following program: int insert(int *array, int arraySize, int newElement) { array[arraySize + 1] = ne开发者_运维知识库wElement;

I have the following program:

int insert(int *array, int arraySize, int newElement)
{
   array[arraySize + 1] = ne开发者_运维知识库wElement;
   return (arraySize+1);     // Return new Array size......
}
int main()
{
   int array[] = {1,2,3,4,5};
   int arraySize = sizeof(array) / sizeof(int);

   insertInArray(array, arraySize,6);
   print(array);
}

I am trying to work out this program in C, but when I print the array after insertion, it doesn't print the desired output.

Please correct me if I am doing something wrong.

Updated Code:

int insert(int **array, int arraySize, int newElement)
{
   int i;    
   *array = realloc(*array,++arraySize * sizeof(int));    
   (*array)[arraySize] = newElement;    
   return (arraySize);
}

int main()
{
   int i;
   int arraySize = 5;
   int *array = (int *)malloc(arraySize * sizeof(int));
   for(i=1; i<=arraySize; i++)
      array[i] = i;

   printArray(array, arraySize);
   arraySize = insert(&array, arraySize,6);
   printArray(array, arraySize);
}


You can't just extend the size of a C array like that; it's not dynamic in that respect; not at all. You have to explicitly reallocate memory. The situation is further complicated by the fact that memory can be allocated in two ways in C: from the stack (local variables in functions) and from the heap (calls to malloc). (Actually I guess it's three ways, if you include globals/statics.)

Thus there are two things that need to change:

  1. If you want to work only with simple arrays, and not structures that contain the array and some size indication, your "insert" function will have to allocate new memory and copy the old array values to it
  2. Arrays to be manipulated by that function should be allocated from the heap.


First of all, this will cause a buffer overflow (by two):

You've allocated room for 5 integers (last index 4). Then:

array[arraySize + 1] = newElement;

writes to index 6, which is two past the end of the array. If you want to change the size of arrays, you need to use realloc., and your function needs a different signature so it can modify the pointer. Something like (omitting error-checking):

int insert(int **array, int arraySize, int newElement)
{
  *array = realloc(*array, ++arraySize * sizeof(int));
  (*array)[arraySize - 1] = newElement;
  return arraySize;     // Return new Array size......
}

int arraySize = 5;
int *array = malloc(arraySize * sizeof(int));
for(int i = 0; i < arraySize; i++)
{
  array[i] = i + 1;
}

arraySize = insert(&array, arraySize, 6);

Second, it's not clear how you expect print to work in general, without knowing the size. When you pass an array to a function, you have to either pass the length or terminate the array in an agreed way (e.g. with NULL or 0).

0

精彩评论

暂无评论...
验证码 换一张
取 消