Deleting element in array

Posted on 2003-03-14
Medium Priority
Last Modified: 2010-04-15
I have another question that's been bothering me and it concerns Arrays.

How do you delete a single element from a dynamic array that I've allocated some memory to?

I'm trying the following code, where count is the size of the array and I want to delete the (a-1)th element, and it doesn't work:

    int *arr;
    int a;

    arr=realloc(arr, count*sizeof(int));

Help again, thanks.
Question by:atariq
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 15

Accepted Solution

efn earned 60 total points
ID: 8141085
You're just moving arr[a] to arr[a - 1].  If you want to get the effect of deleting arr[a - 1], you should move arr[a] through arr[count - 1] to arr[a - 1] through arr[count - 2].

For example, if arr contains

1 2 3 4 5

and a == 3, your code would give

1 2 4 4 5

and then truncate to

1 2 4 4

whereas you want to move the 5 down too, so you get

1 2 4 5 5

and then truncate to

1 2 4 5

Author Comment

ID: 8141962
Thanks for that, I was thinking along the same lines too, but you made it clearer.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
Suggested Courses
Course of the Month11 days, 11 hours left to enroll

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question