?
Solved

Deleting element in array

Posted on 2003-03-14
2
Medium Priority
?
206 Views
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+(a-1))=*(arr+a);
    count--;

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

Help again, thanks.
0
Comment
Question by:atariq
2 Comments
 
LVL 15

Accepted Solution

by:
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
0
 

Author Comment

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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

616 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