Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
no se puede imprimir la salida de una función que devuelve un puntero de matriz en C

Estoy tratando de crear una función que convierta una cadena hexadecimal en una matriz de bytes hexadecimales. Ejemplo: str = "1c01" -> hex_bytes = { 0x1c, 0x01 } .

Cuando trato de imprimir los valores hexadecimales, todo lo que obtengo son 0. Estoy pensando que tiene algo que ver con mis punteros, pero no estoy seguro. Cualquier ayuda sería muy apreciada.

 #include <stdio.h> #include <stdlib.h> #include <string.h> const char *input_1 = "1c0111001f010100061a024b53535009181c"; unsigned int *str_to_hexbytes(const char *hex_str) { size_t len = strlen(hex_str); unsigned int *hex = malloc(sizeof(unsigned int)* len / 2); for(int i, j = 0; i < len; i += 2, j++) { char tmp[2]; strncpy(tmp, hex_str + i, 2); hex[j] = strtol(tmp, NULL, 16); } return hex; } int main(void) { size_t len = strlen(input_1) / 2; unsigned int *hex = str_to_hexbytes(input_1); for (int i = 0; i < len; i++) { printf("%x ", hex[i]); } return 0; }
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

tmp solo tiene suficiente espacio para almacenar los dos caracteres que copia. No tiene espacio para que un byte nulo termine la cadena y, de hecho, strncpy no escribirá ese byte nulo ya que no encontró uno en los dos caracteres. leyó

Como resultado, la función strtol lee más allá del final de la matriz, lo que desencadena un comportamiento indefinido .

Haga que tmp 3 caracteres y agregue el byte nulo manualmente.

Además, solo estás inicializando j , no i , así que asegúrate de hacerlo también.

 for(int i = 0, j = 0; i < len; i += 2, j++) { char tmp[3]; strncpy(tmp, hex_str+i, 2); tmp[2]=0; hex[j] = strtol(tmp, NULL, 16); }
over 4 years ago · Santiago Trujillo Report

0

No está inicializando i con 0. Ese podría ser su problema. int i, j = 0; solo cambia el valor de j a cero, i sigue siendo basura ya que se asigna desde la pila.

También algunas sugerencias:

  • Como también está utilizando la longitud de la cadena en main, solo puede calcularla en main y enviarla a la función.
  • Usaste un 'malloc' que requiere que también llames 'gratis'. Una vez que haya terminado de usar el puntero, llame free(hex)
  • Iterar hasta len - 1 ya que está usando un bloque de memoria por delante en el cuerpo de su bucle for.
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!