Ir ao conteúdo

Matheus Maldi

Membro Pleno
  • Posts

    541
  • Cadastrado em

  • Última visita

Tudo que Matheus Maldi postou

  1. Se o criterio fosse nome e depois idade(aquele inteiro considerei como idade): int pessoa_cmp(const void* pessoa1, const void* pessoa2) { Pessoa* p1 = (Pessoa*)pessoa1; Pessoa* p2 = (Pessoa*)pessoa2; int strcmp_result = strcmp(p1->nome, p2->nome); if (strcmp_result > 0) return 1; if (strcmp_result < 0) return -1; if (p1->idade > p2->idade) return 1; if (p1->idade < p2->idade) return -1; return 0; } Bom, acho que está havendo algum mal entendido, mas considerando o codigo original, considere a entrada: ////// ENTRADA: TURMA1 2 TIAGO 3 ANA 9 TURMA2 3 MARCELO 3 CAROL 10 JOSE 3 ///// SAIDA: TURMA2 3 JOSE TURMA2 3 MARCELO TURMA1 3 TIAGO TURMA1 9 ANA TURMA2 10 CAROL Ele ordenou primeiro pelo numero, e depois pelo nome
  2. Não precisa, o algoritmo que fiz está ordenando perfeitamente, primeiro os numeros e se forem igual por nome.
  3. Primeiro faça o teste com hardded code em vez de ficar fazendo scanf, isso vai acelerar o teste int main() { int vet[5] = { 5, 4, 3, 2, 1 }; seu_quick_sort(vet, 0, 4); // faça um for para printar o loop return 0; } adicionado 14 minutos depois Segue um codigo simples do quick sort para int: void quick_sort_int (int* array, int i_lo, int i_hi) { int lo = i_lo, hi = i_hi; int mid = array[((lo + hi) >> 1)]; do { while (array[lo] < mid) ++lo; while (array[hi] > mid) --hi; if (lo <= hi) { int temp = array[lo]; array[lo] = array[hi]; array[hi] = temp; lo++; hi--; } } while (lo < hi); if (hi > i_lo) quick_sort_int (array, i_lo, hi); if (lo < i_hi) quick_sort_int (array, lo, i_hi); } e agora um código extremamente complexo de quicksort genérico, este codigo faz: Usa insertion_sort caso o range a ser ordenado é menor que 128 (ganha um pouco de perforçance) Seleciona entre index menor, meio e maior, qual será o pivo. Consegue evitar varias chamadas recursivas. static inline void swap (void* l, void* r, size_t size) { if (size == sizeof(__int64_t)) { __int64_t temp = *(__int64_t*)l; *(__int64_t*)l = *(__int64_t*)r; *(__int64_t*)r = temp; } else if (size == sizeof(__int32_t)) { __int32_t temp = *(__int32_t*)l; *(__int32_t*)l = *(__int32_t*)r; *(__int32_t*)r = temp; } else if (size == sizeof(__int16_t)) { __int16_t temp = *(__int16_t*)l; *(__int16_t*)l = *(__int16_t*)r; *(__int16_t*)r = temp; } else if (size == sizeof(__int8_t)) { __int8_t temp = *(__int8_t*)l; *(__int8_t*)l = *(__int8_t*)r; *(__int8_t*)r = temp; } else { char *l_ptr = l, *r_ptr = r; do { char tmp = *l_ptr; *l_ptr++ = *r_ptr; *r_ptr++ = tmp; } while (--size > 0); } } static inline void insertion_sort (void* a_lo, void* a_hi, const size_t size_of_element, int (*cmp)(const void*, const void*)) { for (void* i = a_lo + size_of_element; i <= a_hi; i += size_of_element) { for (void* key = i; key > a_lo && cmp (key - size_of_element, key) > 0; key -= size_of_element) swap(key, key - size_of_element, size_of_element); } } static inline void sort_3 (void* left, void* mid, void* right, const size_t size_of_element, int (*cmp)(const void*, const void*)) { if (cmp (mid, left) < 0) swap (left, mid, size_of_element); if (cmp (right, mid) < 0) swap (right, mid, size_of_element); else return; if (cmp (mid, left) < 0) swap (left, mid, size_of_element); } void quick_sort_g (void* restrict address_lo, void* restrict address_hi, const size_t size_of_element, int (*cmp)(const void*, const void*)) { skip_recursive_call:; // real len is (address_hi - address_lo) / size_of_element + size_of_element; // but is not important here; size_t len = (address_hi - address_lo) / size_of_element; if (len <= 128) { insertion_sort (address_lo, address_hi, size_of_element, cmp); return; } register void* a_lo = address_lo; register void* a_hi = address_hi; register void* mid = address_lo + (len >> 1) * size_of_element; sort_3 (a_lo, mid, a_hi, size_of_element, cmp); a_lo += size_of_element; a_hi -= size_of_element; do { while (cmp (a_lo, mid) < 0) a_lo += size_of_element; while (cmp (a_hi, mid) > 0) a_hi -= size_of_element; if (a_lo <= a_hi) { swap (a_lo, a_hi, size_of_element); if (mid == a_lo) mid = a_hi; else if (mid == a_hi) mid = a_lo; a_lo += size_of_element; a_hi -= size_of_element; } } while (a_lo < a_hi); if (a_hi > address_lo) { if (a_lo < address_hi) { quick_sort_g (address_lo, a_hi, size_of_element, cmp); address_lo = a_lo; goto skip_recursive_call; } else { address_hi = a_hi; goto skip_recursive_call; } } else if (a_lo < address_hi) { address_lo = a_lo; goto skip_recursive_call; } } void quick_sort (const void * pbase, size_t total_elems, size_t size, int (*cmp)(const void*, const void*)) { void *first = (void*)pbase; void* last = first + (total_elems - 1) * size; quick_sort_g (first, last, sizeof(int), cmp); } int intvoidcmp (const void* l, const void* r) { int l_int = *(int*)l; int r_int = *(int*)r; if (l_int > r_int) return 1; if (l_int < r_int) return -1; return 0; } int main () { int array_length = 1024 * 1024 * 10; int *array = (int*)calloc (array_length, sizeof(int)); srand (1024); for (int i = 0; i < array_length; i++) array[i] = rand(); quick_sort (array, array_length, sizeof(int), intvoidcmp); for (int i = 1; i < array_length; i++) if (array[i - 1] > array[i]) printf ("Fail %p -> %d\n", &array[i], array[i]); return 0; }
  4. Com realoc, reduzindo grande quantidade de código: #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { char* turma; char nome[100]; int idade; } Pessoa; int pessoa_cmp(const void* pessoa1, const void* pessoa2) { Pessoa* p1 = (Pessoa*)pessoa1; Pessoa* p2 = (Pessoa*)pessoa2; if (p1->idade > p2->idade) return 1; else if (p1->idade < p2->idade) return -1; return strcmp(p1->nome, p2->nome); } int main() { char turma1_buffer[100]; scanf("%s", turma1_buffer); size_t turma1_length; scanf("%lu", &turma1_length); Pessoa* turma1 = (Pessoa*)calloc(turma1_length, sizeof(Pessoa)); for (size_t i = 0; i < turma1_length; i++) { turma1[i].turma = turma1_buffer; scanf("%s%d", &(turma1[i].nome), &(turma1[i].idade)); } char turma2_buffer[100]; scanf("%s", turma2_buffer); size_t turma2_length; scanf("%lu", &turma2_length); size_t turma1e2_length = turma1_length + turma2_length; Pessoa* turma1e2 = (Pessoa*)realloc(turma1, sizeof(Pessoa) * (turma1e2_length)); for (size_t i = turma1_length; i < turma1e2_length; i++) { turma1e2[i].turma = turma2_buffer; scanf("%s%d", &(turma1e2[i].nome), &(turma1e2[i].idade)); } qsort(turma1e2, turma1e2_length, sizeof(Pessoa), pessoa_cmp); for (size_t i = 0; i < turma1e2_length; i++) printf("%s %d %s\n", turma1e2[i].turma, turma1e2[i].idade, turma1e2[i].nome); free(turma1e2); return 0; }
  5. Coloquei 100 caracteres para o titulo da TURMA, devido a falta o enunciado, mas precavi que poderia ser passado em vez de TURMA1 e TURMA2 for passado MATEMATICA e FISICA Seu compilador não se queixou de nada tipo "unreachable code" com esse return perdido ao final do código? Se a idade for IGUAL, não vai entrar em nenhum dos IFs, ele returna a comparação do texto. o Codigo é localizavel. Referente a alocação da turma, está certo, tem excesso de copias. #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { char* turma; char nome[100]; int idade; } Pessoa; int pessoa_cmp(const void* pessoa1, const void* pessoa2) { Pessoa* p1 = (Pessoa*)pessoa1; Pessoa* p2 = (Pessoa*)pessoa2; if (p1->idade > p2->idade) return 1; else if (p1->idade < p2->idade) return -1; return strcmp(p1->nome, p2->nome); } int main() { char turma1_buffer[100]; scanf("%s", turma1_buffer); size_t turma1_length; scanf("%lu", &turma1_length); Pessoa* turma1 = (Pessoa*)calloc(turma1_length, sizeof(Pessoa)); for (size_t i = 0; i < turma1_length; i++) { turma1[i].turma = turma1_buffer; scanf("%s%d", &(turma1[i].nome), &(turma1[i].idade)); } char turma2_buffer[100]; scanf("%s", turma2_buffer); size_t turma2_length; scanf("%lu", &turma2_length); Pessoa* turma2 = (Pessoa*)calloc(turma2_length, sizeof(Pessoa)); for (size_t i = 0; i < turma2_length; i++) { turma2[i].turma = turma2_buffer; scanf("%s%d", &(turma2[i].nome), &(turma2[i].idade)); } size_t turma1e2_length = turma1_length + turma2_length; Pessoa* turma1e2 = (Pessoa*)calloc(turma1e2_length, sizeof(Pessoa)); memcpy(turma1e2, turma1, turma1_length * sizeof(Pessoa)); memcpy(turma1e2 + turma1_length, turma2, turma2_length * sizeof(Pessoa)); qsort(turma1e2, turma1e2_length, sizeof(Pessoa), pessoa_cmp); for (size_t i = 0; i < turma1e2_length; i++) printf("%s %d %s\n", turma1e2[i].turma, turma1e2[i].idade, turma1e2[i].nome); free(turma1); free(turma2); free(turma1e2); return 0; }
  6. #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { char turma[100]; char nome[100]; int idade; } Pessoa; int pessoa_cmp(const void* pessoa1, const void* pessoa2) { Pessoa* p1 = (Pessoa*)pessoa1; Pessoa* p2 = (Pessoa*)pessoa2; if (p1->idade > p2->idade) return 1; else if (p1->idade < p2->idade) return -1; return strcmp(p1->nome, p2->nome); } int main() { char buffer[8192]; scanf("%s", buffer); size_t turma1_length; scanf("%lu", &turma1_length); Pessoa* turma1 = (Pessoa*)calloc(turma1_length, sizeof(Pessoa)); for (size_t i = 0; i < turma1_length; i++) { memcpy(turma1[i].turma, buffer, 100 * sizeof(char)); scanf("%s%d", &(turma1[i].nome), &(turma1[i].idade)); } scanf("%s", buffer); size_t turma2_length; scanf("%lu", &turma2_length); Pessoa* turma2 = (Pessoa*)calloc(turma2_length, sizeof(Pessoa)); for (size_t i = 0; i < turma2_length; i++) { memcpy(turma2[i].turma, buffer, 100 * sizeof(char)); scanf("%s%d", &(turma2[i].nome), &(turma2[i].idade)); } size_t turma1e2_length = turma1_length + turma2_length; Pessoa* turma1e2 = (Pessoa*)calloc(turma1e2_length, sizeof(Pessoa)); memcpy(turma1e2, turma1, turma1_length * sizeof(Pessoa)); memcpy(turma1e2 + turma1_length, turma2, turma2_length * sizeof(Pessoa)); qsort(turma1e2, turma1e2_length, sizeof(Pessoa), pessoa_cmp); for (size_t i = 0; i < turma1e2_length; i++) printf("%s %d %s\n", turma1e2[i].turma, turma1e2[i].idade, turma1e2[i].nome); free(turma1); free(turma2); free(turma1e2); return 0; } Este é o Código, funcionou para o input apresentado.
  7. Este é meu programa de Jogo da Velha, uma implementação que fiz a alguns anos, possui: Algoritmo AlphaBeta Minimax para jogar. Tabuleiro em BitBoard. Segue o Código: #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> typedef enum { None = 0, TL = 1, TC = 2, TR = 4, ML = 8, MC = 16, MR = 32, BL = 64, BC = 128, BR = 256, TopRow = TL | TC | TR, MiddleRow = ML | MC | MR, BottomRow = BL | BC | BR, LeftColumn = TL | ML | BL, CenterColumn = TC | MC | BC, RightColumn = TR | MR | BR, Diagonal1 = TL | MC | BR, Diagonal2 = TR | MC | BL, All = TopRow | MiddleRow | BottomRow } GridCells; typedef struct { GridCells Current; GridCells Opponent; bool CurrentIsO; } Grid; typedef struct { int count; GridCells items[9]; } EnumerableGridCells; Grid ttt_new_grid(GridCells current, GridCells opponent, bool isO); Grid ttt_new_grid_empty(void); bool ttt_check(GridCells state, GridCells target); bool ttt_can_move(const Grid* grid, GridCells target); bool ttt_make_move(Grid* grid, GridCells target); bool ttt_check_win(GridCells target); bool ttt_current_is_loser(const Grid* this); bool ttt_is_draw(const Grid* grid); bool ttt_is_finished(const Grid* grid); Grid ttt_make_move_new_grid(Grid* grid, GridCells target); void ttt_get_moves(const Grid* grid, EnumerableGridCells* valid_moves); int alphabeta_minimax(Grid* grid, GridCells* best); void ttt_print_grid(const Grid* this); void ttt_human_player(Grid* grid, GridCells* target); void ttt_ia_player(Grid* grid, GridCells* target); void ttt_new_game(void (*player1)(Grid*, GridCells*), void (*player2)(Grid*, GridCells*)); bool want_new_game(); int main() { bool player1_is_human = true; while (true) { if (player1_is_human) ttt_new_game(ttt_human_player, ttt_ia_player); else ttt_new_game(ttt_ia_player, ttt_human_player); if (!want_new_game()) break; player1_is_human = !player1_is_human; } return 0; } Grid ttt_new_grid(GridCells current, GridCells opponent, bool isO) { Grid result; result.Current = current; result.Opponent = opponent; result.CurrentIsO = isO; return result; } Grid ttt_new_grid_empty() { Grid result; result.Current = None; result.Opponent = None; result.CurrentIsO = false; return result; } inline bool inline_ttt_check(GridCells state, GridCells target) { return (state & target) == target; } bool ttt_check(GridCells state, GridCells target) { return (state & target) == target; } bool ttt_can_move(const Grid* grid, GridCells target) { if (target == None) return false; if (ttt_check(grid->Current, target)) return false; if (ttt_check(grid->Opponent, target)) return false; return true; } bool ttt_make_move(Grid* grid, GridCells target) { if (!ttt_is_finished(grid) && ttt_can_move(grid, target)) { *grid = ttt_new_grid(grid->Opponent, grid->Current | target, !grid->CurrentIsO); return true; } return false; } Grid ttt_make_move_new_grid(Grid* grid, GridCells target) { return ttt_new_grid(grid->Opponent, grid->Current | target, !grid->CurrentIsO); } bool ttt_check_win(GridCells target) { if (ttt_check(target, TopRow)) return true; if (ttt_check(target, MiddleRow)) return true; if (ttt_check(target, BottomRow)) return true; if (ttt_check(target, LeftColumn)) return true; if (ttt_check(target, CenterColumn)) return true; if (ttt_check(target, RightColumn)) return true; if (ttt_check(target, Diagonal1)) return true; if (ttt_check(target, Diagonal2)) return true; return false; } bool ttt_current_is_loser(const Grid* grid) { return ttt_check_win(grid->Opponent); } bool ttt_is_draw(const Grid* grid) { if (!ttt_check(grid->Opponent | grid->Current, All)) return false; return !ttt_current_is_loser(grid); } bool ttt_is_finished(const Grid* grid) { return ttt_is_draw(grid) || ttt_current_is_loser(grid); } void ttt_get_moves(const Grid* grid, EnumerableGridCells* valid_moves) { valid_moves->count = 0; if (ttt_current_is_loser(grid)) return; GridCells occupation = grid->Current | grid->Opponent; if (!ttt_check(occupation, MC)) valid_moves->items[valid_moves->count++] = MC; if (!ttt_check(occupation, TL)) valid_moves->items[valid_moves->count++] = TL; if (!ttt_check(occupation, TR)) valid_moves->items[valid_moves->count++] = TR; if (!ttt_check(occupation, BL)) valid_moves->items[valid_moves->count++] = BL; if (!ttt_check(occupation, BR)) valid_moves->items[valid_moves->count++] = BR; if (!ttt_check(occupation, ML)) valid_moves->items[valid_moves->count++] = ML; if (!ttt_check(occupation, MR)) valid_moves->items[valid_moves->count++] = MR; if (!ttt_check(occupation, TC)) valid_moves->items[valid_moves->count++] = TC; if (!ttt_check(occupation, BC)) valid_moves->items[valid_moves->count++] = BC; } static int alphabeta_minimax_depth(Grid* grid, GridCells* best, int alpha, int beta, int depth) { *best = None; int bestResult = -10; GridCells garbage; if (ttt_current_is_loser(grid)) return -10 + depth; if (ttt_is_draw(grid)) return 0; EnumerableGridCells moves; ttt_get_moves(grid, &moves); int i; for (i = 0; i < moves.count; i++) { int move = moves.items[i]; Grid other = ttt_make_move_new_grid(grid, move); alpha = -alphabeta_minimax_depth(&other, &garbage, -beta, -alpha, depth + 1); if (beta <= alpha) return alpha; if (alpha > bestResult) { *best = move; bestResult = alpha; } } return bestResult; } int alphabeta_minimax(Grid* grid, GridCells* best) { return alphabeta_minimax_depth(grid, best, -10, +10, 1); } static char ttt_get_char(const Grid* grid, GridCells target) { if (ttt_check(grid->Current, target)) return grid->CurrentIsO ? 'O' : 'X'; if (ttt_check(grid->Opponent, target)) return grid->CurrentIsO ? 'X' : 'O'; return ' '; } void ttt_print_grid(const Grid* this) { printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printf(" | | \n"); printf(" %c | %c | %c \n", ttt_get_char(this, TL), ttt_get_char(this, TC), ttt_get_char(this, TR)); printf(" | | \n"); printf("-----------------\n"); printf(" | | \n"); printf(" %c | %c | %c \n", ttt_get_char(this, ML), ttt_get_char(this, MC), ttt_get_char(this, MR)); printf(" | | \n"); printf("-----------------\n"); printf(" | | \n"); printf(" %c | %c | %c \n", ttt_get_char(this, BL), ttt_get_char(this, BC), ttt_get_char(this, BR)); printf(" | | \n"); } size_t get_char_buffer(char* buffer, size_t size) { size_t index = 0; int c; while ((c = fgetc(stdin)) != '\r' && c != '\n' && c != EOF) if (index + 1 < size) buffer[index++] = c; if (c == '\r' && (c = fgetc(stdin)) != '\n' && c != EOF) ungetc(c, stdin); buffer[index] = '\0'; return index; } void ttt_human_player(Grid* grid, GridCells* target) { printf("Entre com o lance: "); do { char buffer[3]; get_char_buffer(buffer, 3); if (strcmp(buffer, "1") == 0 || strcmp(buffer, "TL") == 0) *target = TL; else if (strcmp(buffer, "2") == 0 || strcmp(buffer, "TC") == 0) *target = TC; else if (strcmp(buffer, "3") == 0 || strcmp(buffer, "TR") == 0) *target = TR; else if (strcmp(buffer, "4") == 0 || strcmp(buffer, "ML") == 0) *target = ML; else if (strcmp(buffer, "5") == 0 || strcmp(buffer, "MC") == 0) *target = MC; else if (strcmp(buffer, "6") == 0 || strcmp(buffer, "MR") == 0) *target = MR; else if (strcmp(buffer, "7") == 0 || strcmp(buffer, "BL") == 0) *target = BL; else if (strcmp(buffer, "8") == 0 || strcmp(buffer, "BC") == 0) *target = BC; else if (strcmp(buffer, "9") == 0 || strcmp(buffer, "BR") == 0) *target = BR; else *target = None; } while(!ttt_can_move(grid, *target)); } void ttt_ia_player(Grid* grid, GridCells* target) { alphabeta_minimax(grid, target); } void ttt_new_game(void (*player1)(Grid*, GridCells*), void (*player2)(Grid*, GridCells*)) { Grid grid_game = ttt_new_grid_empty(); bool current_player1 = true; while (!ttt_is_finished(&grid_game)) { ttt_print_grid(&grid_game); GridCells move = None; if (current_player1) player1(&grid_game, &move); else player2(&grid_game, &move); grid_game = ttt_make_move_new_grid(&grid_game, move); current_player1 = !current_player1; } ttt_print_grid(&grid_game); printf("Jogador %c ganhou!\n\n\n", grid_game.CurrentIsO ? 'X' : 'O'); } bool want_new_game() { while (true) { printf("Novo jogo [Y/N]? "); char buffer[2]; get_char_buffer(buffer, 2); if (strcmp(buffer, "Y") == 0 || strcmp(buffer, "y") == 0) return true; if (strcmp(buffer, "N") == 0 || strcmp(buffer, "n") == 0) return false; } }
  8. Instala neste link https://dotnet.microsoft.com/download Download .Net Core SDK
  9. Inclua o header <stdint>h e utilize int64_t em vez de long ou long long, devido as incompatibilidade nos compiladores e arquitetura. Por exemplo nos compiladores que uso long tem 64 bits, já você deve estar utilizando compilação em 32 bits. adicionado 7 minutos depois Não utilize isso, meu compilador retorna 18446744073709551615 para ULONG_MAX . Utilize assim: #include <stdio.h> #include <stdlib.h> #include <stdint.h> int main(int argc, char** argv) { printf("sizeof(long long int) = %d bytes\n", sizeof(long long int)); printf(" 0 1 2 2\n", UINT64_MAX); printf(" 0 5 0 5 0 5\n", UINT64_MAX); printf("(8) v = %20u\n", UINT8_MAX); printf("(16) v = %20u\n", UINT16_MAX); printf("(32) v = %20lu\n", UINT32_MAX); printf("(64) v = %20llu\n", UINT64_MAX); return 0; }
  10. O custo do ! (not) para um retorno de verdadeiro ou falso é ZERO. testando os código abaixo no godbolt temos o resultado do binário idêntico: #include <stdio.h> int main(int argc, char** argv) { char c = argv[0][0]; // Necessario para o compilador não eliminar tudo while ( (c != 'm') && (c != 'f') ) // while (!((c == 'm') || (c == 'f'))) printf("%c", c); return 0; } e assembly gerado com as flags -O3: main: push rbx mov rax, QWORD PTR [rsi] movsx ebx, BYTE PTR [rax] cmp bl, 109 je .L2 cmp bl, 102 je .L2 .L3: mov edi, ebx call putchar jmp .L3 .L2: xor eax, eax pop rbx ret
  11. while (!((c == 'm') || (c == 'f'))) Isso que você queria
  12. Este é um bom link de referencia: https://www.viva64.com/en/a/0050/ Referente ao uso do size_t para guardar tamanhos, muito improvável que terá problema em utilizar para isso, mas recomendaria usar as definições do stdint.h, int**SIZE**_t ou uint**SIZE**_t. Pois vai saber exatamente o tamanho. Veja o exemplo deste link https://primesieve.org/segmented_bit_sieve.cpp Ele usa uint64_t, se tivesse usado size_t o programa funcionaria normalmente em x64, mas não funcionaria em 32bit.
  13. Sim, é um size que foi criado com intuito de manter a compatibilidade dos códigos para compiladores de 32 e 64 bits, principalmente nas funções de memoria, endereço de memoria e aritmética de ponteiros, se fosse simplesmente um size, poderias ter outros tipos como size8_t, size_16_t, size32_t ... Se você tem que guardar um size de alguma coisa que nunca vai passar de 255, não faz sentido usar size_t e sim uint8_t. E por fim, qual o unico motivo que mudo a tamanho do size_t? A mudança do tamanho maximo da memoria. Em nenhum outros caso.
  14. Claro que tem tudo a ver, size_t é um tipo que pode conter qualquer índice de um array, todas as funções que você citou receber um size_t devido a trabalharem como endereços de memoria que podem conter tamanhos de até size_t, não foi simplesmente criado para facilitar o uso de um unsigned int ou long ou long long. Veja que é unsigned justamente devido ao tamanho do array não poder ser negativo,e ptrdiff_t é signed devido a diferença entre endereços de memoria poderem ser negativos, veja que como você mostrou ai, a declaração esta perto de ptrdiff_t e intptr_t por estar relacionado, não simplesmente porque um programador da microsoft resolveu colocar ele ai um tipo para facilitar. Que alias, não deveria estar neste header e sim no stddef.h conforme a ISO. Quando precisarmos mudar a arquitetura de 64 para 128 bits, será porque foi necessário endereçar mais que 18.4 exabytes, o que não cabe em um ponteiro de tamanho de 8 bytes, e por isso será necessário mudar o tamanho do size_t.
  15. Mas o que DEVE estar no header é o exato tamanho que o ponteiro tem, no caso de x64 é 8 bytes e nos 32 bits 4 bytes, isso porque a função de malloc recebe como paramentro um size_t, se na arquitetura de 64 bits o size_t fosse de 32 bit, teriamos como valor maximo 4294967295, e isso nos iria impedir de alocar mais que 4GB para um endereço. Queremos matar binarios de 32 bits devido a necessidade de manter bibliotecas iguais para as 2 arquiteturas.
  16. Note que ele aloca pelo menos 8 bytes a mais (64bits) para incluir o valor que foi alocado, o restante alocado a mais deve ser para manter algum alinhamento bom na memoria., por este motivo a função free não tem valor a ser deletado. Pode saber um pouco mais em: https://www.geeksforgeeks.org/g-fact-88/?ref=rp adicionado 17 minutos depois size_t é um unsigned tamanho do ponteiro, mude o compilador para x64 e nos ajude a matar binarios de 32 bits.
  17. Exatamente o valor que você pediu não é possível, mas é possível saber quanto de memoria que a implementação de malloc que você usou allocou, o valor está nos 64 bits anteriores ao ponteiro para um arquitetura 64 bits, e 32 para a arquitetura 32 bits, pode existir implementações de malloc que não funcionem dessa maneira. #include <stdio.h> #include <stdlib.h> #include <stdint.h> size_t malloc_size(void* addr) { size_t* size_addr = (size_t*)addr; return size_addr[-1]; } int main() { for (size_t i = 1; i <= 1000; i++) { void* ptr = (void*)malloc(sizeof(char) * i); size_t ptr_size = malloc_size(ptr); printf("Pedido: %lu, Allocado: %lu\n", i, ptr_size); free(ptr); } return 0; } Note que você pede um valor e ele te entrega outro.
  18. Recomendaria mudar para o Visual Studio e utilizar o VCPKG para instalar as dependências.
  19. Lembrando que eh possível marcar para compilação estática e assim o binário vai rodar livre de DLLs. A Microsoft nunca escondeu isso, na verdade a comunidade inteiro foi pro .Net assim o MFC acabou sumindo.
  20. A tempos não uso o Windows e Visual Studio, referente a calculadora do windows que você disse é a do windows 10? Ela é de código aberto agora, veja o segredo, MUITA programação, menos de 0,1% do tempo foi gasto na interface: https://github.com/microsoft/calculator/ Programar HTML e CSS na mão é muito melhor que um arrasta e solta, veja que WebForms ou JSF estão morrendo. Você parece querer arrastar e soltar apenas, você critica o .Net de VB e C# mas eles foram criados para pessoas como você, que querem facilidade e produtividade. Veja que ironia. Há 10 anos atrás tinha o mesmo pensamento que você, ficava preocupado em fazer um software que rodasse sem instalador nenhum, mas não conseguia entender a Win32, pois estava acostumado com as facilidade do C#, o gerenciamento de memoria, o editor que ajudava muito. Com o amadurecimento na programação passei a entender a utilidade de cada ferramenta. Se o que você quer é criar interfaces bonitas, aprenda a Win32, e cole este trecho de código para seu app padrão em c++ não fique parecendo uma 'linda' janela igual ao do bloco de notas: #pragma comment(linker,"\"/manifestdependency:type='win32' \ name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \ processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") e por fim acredito que esteja procurando isso:
  21. Primeiro você deve aprender C++, ou C. Sobre produtividade, se você não tem com C ou C++ é porque ainda não sabe programar, Competições como GoogleCodeJam ou CodeForces a maioria das soluções são feitas em C++. Aprender programar C++ não é para qualquer um, veja se você acha que o código que o visual studio emite quando criar uma janela em Win32 é na verdade como a API funciona no seu baixo nível. Arrastar os widgets no form não é programar.
  22. scanf(%f, %cfab); use &cfab e não %
  23. Trabalho por que? É possivel fazer scripts no windows, e IDE só ajuda. Já utilizou SH para ler tabelas de Banco de Dados? Dá pra fazer mas é uma porcaria. Com o PS que é baseado em objetos, fica muito fácil. infelizmente o SH ainda não tem esse suporte.
  24. As 'inutilidade' são faceis de resolver, não use, é melhor sobrar do que faltar. A velocidade de compilação é a mesma com e sem o VS aberto. Você pode usar o Visual Studio e não ficar preso no .net. PowerShell é muito superior ao sh.
  25. Configurei a variavel no meu PC public class Program { public static void main(String[] args) { System.out.println("Hello World!"); } } o programa acima está num arquivo Program.java, compilei e executei assim: PS C:\Users\msmaldi\Documents\JavaProject> javac .\Program.java PS C:\Users\msmaldi\Documents\JavaProject> java Program Hello World! as chamadas abaixo NÃO funcionaram. java Program.class java Program.java

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...