如何将char数组转换为int数组?

时间:2020-07-23 04:47:51

标签: arrays c embedded

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stats.h"

/* Size of the Data Set */
#define SIZE (40)

void print_array (unsigned char *p, int l) {
    int i;  
    for (i=0;i<l;i++) {
        printf("%d\t",*p);
        p++;    
    }
    
}
void print_array_int (int *p, int l) {
    int i;  
    for (i=0;i<l;i++) {
        printf("%d\t",*p);
        p++;    
    }
    
}
void typecasting(unsigned char test[SIZE], int array[SIZE]) {
    int i=0;
    unsigned char *token = strtok(test,",");
    while (token) {
        if(i<SIZE) {
        array[i++] = atoi(token);
        }
    token = strtok(NULL,",");
    }
}
void main() {
  int array[SIZE] = {};
  unsigned char test[SIZE] = {34,201,190,154,8,194,2,6,114,88,45,76,123,87,25,23,200,122,150,90,92,87,177,244,201,6,12,60,8,2,5,67,7,87,250,230,99,3,100,90};



  /* Other Variable Declarations Go Here */
  /* Statistics and Printing Functions Go Here */
print_array(test, SIZE);
typecasting(test,array);
print_array_int(array,SIZE);
}

我在这段代码中想要将char数组转换为int数组。 以前,我尝试通过使用指针来执行此操作,但是没有用,它显示了堆栈粉碎错误。我想将此char数组转换为int数组以执行一些数学运算。

1 个答案:

答案 0 :(得分:2)

您太努力了。这是类型转换的外观

void typecasting(unsigned char test[SIZE], int array[SIZE]) {
    for (int i = 0; i < SIZE; ++i)
        array[i] = test[i];
}

如果您是从C字符串转换的,即您的原始测试数组是

,则您的代码可能是合适的

char test[] = "34,201,190,154,8,194,2,6,114,88,45,76,123,87,25,23,...";

因此,我想您可能会说您误解了C ++中char(和unsigned char)的本质。它们可以代表char greeting[] = "hello";中的字符数据,也可以代表char test[] = {1,2,3};中的小整数。