Deleting and shifting elements in an array

This is a discussion on Deleting and shifting elements in an array within the C Programming forums, part of the General Programming Boards category; suppose an array is initialized as s[]={1, 2, 3, 4, 5} i would like to delete elements 1 to 3.. ...

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    3

    Deleting and shifting elements in an array

    suppose an array is initialized as s[]={1, 2, 3, 4, 5}

    i would like to delete elements 1 to 3.. i.e 2, 3 and 5..

    the remaining array has to look like s[]= {1, 5}

    how can this be done?

  2. #2
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    An array is not a particularly well suited data structure for that operation. What you want is a linked list.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You can't delete the actual elements of the array (like you can with the nodes of a linked list), but you can remove the VALUES in those array elements.

    If zero means the same as "nothing" in your program, you can use it as your "sentinel" value. I've used INT_MAX and INT_MIN as sentinel values for this purpose. (include <limits.h> to use these macro's).

    Code:
    for(i=low; i<=high;i++)
      myArray[i] = INT_MIN;
    For taking average scores, printing out the array, and what not, you need to adjust all your logic a bit to ignore that sentinel value.

  4. #4
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    You can use memmove().
    e.g memmove(s+1,s+4,sizeof(int) * 1 );

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Deleting characters from 2d arrays
    By `firefox in forum C Programming
    Replies: 4
    Last Post: 05-21-2005, 06:18 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21