简体   繁体   中英

How to assign the whole value of one char array into another array of one position into hex format in C?

I want to store the hexadecimal value format like "0x12" into the array of one position from another array. I am able to change into the hexadecimal string like "0x12" but not able to assign the whole value into the one position of array. Can I know, where I am doing wrong?

    char b[5];
    int a= 20;
    char hex[5];
    sprintf(hex,"0x%d",a);
    printf("hex: %s\n",hex);
    b[0]=hex;
    printf("b[0]: %s\n",b);

Expected result:

hex: 0x20,
b[0]: 0x20

Actual result:

hex: 0x20,
b[0]:

Leaving aside the fact that the hexadecimal equivalent of decimal 20 is 0x14, not 0x20, if you want to store the C-string "0x20" in a single position in an array, then that array has to be an array of allocated char* , or an array of char[] , like so:

Pointers:

int main(int argc, char *argv[]) {
  char **b;
  int i;
  int a = 20;

  b = calloc(5, sizeof *b);
  if (b == NULL) {
    printf("Malloc failed");
    return 1;
  }
  for (i = 0; i < 5; i++) {
    b[i] = malloc(sizeof b[0]);
    if (b[i] == NULL) {
      printf("malloc failed - fatal error");
      // here should be code to free the values that WERE allocated.
      return 1;
    }
  }
  sprintf(b[0], "0x%d", a);
  printf("hex: %s\n", b[0]);
  printf("b[0]: %s\n", b[0]);
  a = 30;
  sprintf(b[1], "0x%d", a);
  printf("hex: %s\n", b[1]);
  printf("b[1]: %s\n", b[1]);
  return 0;
}

Character arrays:

int main(int argc, char* argv[]) {
    char hex1[5];
    char hex2[5];
    char hex3[5];
    char hex4[5];
    char hex5[5];
    char b[5][5] = { hex1, hex2, hex3, hex4, hex5 };
    int a= 20;

    sprintf(b[0],"0x%d",a);
    printf("hex: %s\n",b[0]);
    printf("b[0]: %s\n",b[0]);
    a = 30;
    sprintf(b[1], "0x%d", a);
    printf("hex: %s\n", b[1]);
    printf("b[1] %s\n", b[1]);
  return 0;
}

Or any reasonable combination of the two.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM