1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
// La macro hybride : L'idée du forum (tableau dynamique VLA) + votre sécurité anti-crash (taille >= 1)
#define MID_B(src, start, len) MID(src, (char[((len) > 0 ? (len) : 0) + 1]){0}, start, len)
// Prototype de la fonction
char* MID(const char * string_1, char * string_2, int start, int NBytes);
// Implémentation sécurisée
char* MID(const char * string_1, char * string_2, int start, int NBytes) {
if (string_1 == NULL || string_2 == NULL || start < 0 || NBytes <= 0) {
if (string_2 != NULL) string_2[0] = '\0';
return string_2;
}
int len = (int)strlen(string_1);
if (start >= len) {
string_2[0] = '\0';
return string_2;
}
int k = start;
int l = 0;
for( ; k < len && k < (start + NBytes); k++ ) {
string_2[l++] = string_1[k];
}
string_2[l] = '\0';
return string_2;
}
// Le test de l'extraction multiple
int main(void) {
const char* dataset[] = {
"1082-THOMAS -00468.52-DEL",
"5567-MARTIN -00746.16-INJ",
"2438-DURAND -00213.65-INJ"
};
int num_lines = 3;
printf("=== EXTRACTION MULTIPLE SUR UNE SEULE LIGNE (INLINE) ===\n");
for(int i = 0; i < num_lines; i++) {
const char* line = dataset[i];
// L'épreuve du feu : Deux appels sur la même ligne !
// Aucun risque que le statut n'écrase le nom.
printf("Le statut de '%s' est '%s'\n",
MID_B(line, 5, 10),
MID_B(line, 25, 3));
}
printf("\n=== CALCULS MATHÉMATIQUES SIMULTANÉS ===\n");
// Extrait deux nombres et les additionne directement sur une ligne
const char* ligne_nombres = "0025-0015";
int total = atoi(MID_B(ligne_nombres, 0, 4)) + atoi(MID_B(ligne_nombres, 5, 4));
printf("Addition inline : %s + %s = %d\n",
MID_B(ligne_nombres, 0, 4),
MID_B(ligne_nombres, 5, 4),
total);
return 0;
} |