簡體   English   中英

C編程中刪除結構

[英]Deleting structure in C programming

#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;
}

deleting函數中,我不明白這行是什么: *(ct + j) = ct[j + 1]; 做。 有人可以幫忙嗎? 我希望你理解這個函數,因為這只是整個程序的一個序列。

在這個函數中

void deleting(Calculator *ct, int *dim, char serie[45])

似乎第一個參數被聲明為指向作為參數傳遞給函數的數組第一個元素的指針。

因此

ct[0]

將表示數組的第一個元素

ct[1]

將表示數組的第二個元素,依此類推。

這個記錄

ct[i]

其中 i 是某個索引相當於

*( ct + i )

所以這個說法

*(ct + j) = ct[j + 1]; 

也可以寫成

ct[j] = ct[j + 1]; 

至於功能本身,則完全錯誤。

在這個循環中

        for (j = i;j < (*dim - k);j++)

            *(ct + j) = ct[j + 1]; // <== This line here

據說也可以這樣寫

        for (j = i;j < (*dim - k);j++)

            ct[j] = ct[j + 1]; // <== This line here

當 j 等於*dim - 1時,嘗試在數組之外寫入,因為在這種情況下表達式j + 1將等於*dim盡管索引的有效范圍是[0, *dim - 1]

此外,外循環中的條件也應該至少看起來像

for (i = 0; i < (*dim) - k; i++)
            ^^^^^^^^^^^^^^

並且當數組的一個元素被刪除時,索引i不會增加。 否則將跳過刪除元素之后的下一個元素。

我命名為remove_all的函數的正確實現可以如下所示,如下面的演示程序所示。 我簡化了結構聲明,因為結構的其他數據成員與函數實現無關。

#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;
}

程序輸出是

A B C A D E A 
B C D E 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM