-2

I am making a program where user can edit array. I am new in programming.code is not finished yet.

Can I use calloc(size-1,2)? Is that valid ? Does it creates array size-1?

#include <stdlib.h> 
#include <stdio.h>

 int main()
 {

int *pointer1,*pointer2,size,i,choice,j=0,index;

     printf("Enter Elements of Arrays " );
     scanf("%d",&size);

      pointer1=(int*)calloc(size,2);

     for(i=0;i!=size;i++){
        scanf("%d",pointer1+i);
     }

    printf("Enter your choice \n" );
    scanf("%d",&choice);

      switch(choice) 
     {
     case 0:
         printf("Enter Index for Deletation ");
         scanf("%d",&index);
 /* I know that code is not finish. but calloc(size-1,2) is that valid or not ?*/
         pointer2=(int*)calloc(size-1,2);
         for(i=0;i!=size-1;i++){
            if(i!=index){
             *pointer2+i=*pointer1+i+j;
                    }
                    else{
                 j++;  
              }
             }
                  for(i=0;i<=size;i++)
                  {
              printf("\n%d",*pointer2+i);
            }

           break;

     default:
         printf("Error!");
     } 
  return 0;
 }
  • It might be but it is not the best way. Please read https://stackoverflow.com/questions/7097678/removing-elements-from-dynamic-arrays for better ideas – Antti Haapala -- Слава Україні Sep 05 '18 at 10:03
  • Your `calloc` call seems assume that `sizeof(int)` is 2, which might not be correct and certainly is not portable. If `sizeof(int)` is in fact 2, your `calloc` call allocates space for `size-1` elements, but your loop accesses elements at index `size-1` and `size` which will be beyond the end of the memory allocated by `calloc`. – Ian Abbott Sep 05 '18 at 10:19
  • Your loop is `for(i=0;i<=size;i++)` so you certainly don't want `size-1` elements in the array, you need `size+1` elements. Moreover `pointer1[i+j]` is likely to index beyond the bounds of the memory allocation although we don't see the allocation for `pointer1`. – Weather Vane Sep 05 '18 at 10:20
  • That first loop will never finish as you have `i--` and `i++` cancelling each other out, so it'll get stuck when `i==index` – Chris Turner Sep 05 '18 at 10:27

2 Answers2

0

Function signature for calloc is as below.

void * calloc( size_t num, size_t size );

Make sure that num > 0 and size > 0

Mayur
  • 2,583
  • 16
  • 28
0

Since you do not tell us what is pointer2, it's difficult to answer.

But, if you write:

int *pointer2 = NULL;
size_t size = 10; 

if (size-1 > 0)
{
    pointer2 = calloc(size-1, sizeof *pointer);
}

The pointer2 will points to an portion of memory able to store size-1 integer (int) values.


Mathieu
  • 8,840
  • 7
  • 32
  • 45