Reputation: 17
#include <stdio.h>
#include <conio.h>
#include <string.h>
typedef struct {
char serie_calculator[45];
char tip_procesor[78];
char memorie[55];
char hdd[60];
char monitor[65];
}Calculator;
void deleting(Calculator *ct, int *dim, char serie[45])
{
int k = 0, i, j;
for (i = 0;i<(*dim);i++)
if (strcmp((ct + i)->serie_calculator, serie) == 0)
{
k++;
for (j = i;j < (*dim - k);j++)
*(ct + j) = ct[j + 1]; // <== This line here
}
*dim = *dim - k;
}
In the deleting
function, I don't understand what the line: *(ct + j) = ct[j + 1];
does. Can somebody help? I hope that you understand the function, because this is just a sequence from the whole program.
Upvotes: 1
Views: 7161
Reputation: 310980
In this function
void deleting(Calculator *ct, int *dim, char serie[45])
it seems that the first parameter is declared like a pointer to the first element of the array passed to the function as an argument.
Thus
ct[0]
will denote the first element of the array
ct[1]
will denote the second element of the array and so on.
This record
ct[i]
where i is some index is equivalent to
*( ct + i )
So this statement
*(ct + j) = ct[j + 1];
can be written also like
ct[j] = ct[j + 1];
As for the function itself then it is entirely wrong.
In this loop
for (j = i;j < (*dim - k);j++)
*(ct + j) = ct[j + 1]; // <== This line here
that as it was said can be written also like
for (j = i;j < (*dim - k);j++)
ct[j] = ct[j + 1]; // <== This line here
there is an attempt to write beyond the array when j is equal to *dim - 1
because expression j + 1
in this case will be equal to *dim
though the valid range of indices is [0, *dim - 1]
Also the condition in the outer loop also should look at least like
for (i = 0; i < (*dim) - k; i++)
^^^^^^^^^^^^^^
and the index i
shall not be increased when an element of the array was deleted. Otherwise the next element after the deleted element will be skipped.
A correct implementation of the function that I named like remove_all
can look the following way as it is shown in the demonstrative program below. I simplified the structure declaration because other data members of the structure are irrelevant for the function implementation.
#include <stdio.h>
#include <string.h>
typedef struct
{
char serie_calculator[45];
// ...
} Calculator;
size_t remove_all( Calculator c[], size_t n, const char *s )
{
size_t i = 0;
for ( size_t j = 0; j < n; j++ )
{
if ( !( strcmp( c[j].serie_calculator, s ) == 0 ) )
{
if ( i != j ) c[i] = c[j];
++i;
}
}
return i;
}
int main(void)
{
Calculator c[] = { { "A" }, { "B" }, { "C" }, { "A" }, { "D" }, { "E" }, { "A" } };
const size_t N = sizeof( c ) / sizeof( *c );
for ( size_t i = 0; i < N; i++ ) printf( "%s ", c[i].serie_calculator );
printf( "\n" );
size_t n = remove_all( c, N, "A" );
for ( size_t i = 0; i < n; i++ ) printf( "%s ", c[i].serie_calculator );
printf( "\n" );
return 0;
}
The program output is
A B C A D E A
B C D E
Upvotes: 1