【问题标题】:How to convert array of char into array of int?如何将char数组转换为int数组?
【发布时间】:2020-11-12 18:07:45
【问题描述】:
#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 数组来执行一些数学运算。

【问题讨论】:

  • 在继续之前,最好先研究一下 C#/C++/C 之间的区别,因为你似乎很困惑
  • 转换是什么意思?如果只是保留数值,strtok 和 atoi 在这里没有位置。只需做一个 for(;i

标签: arrays c embedded


【解决方案1】:

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

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}; 表示小整数。

【讨论】:

  • 是的,它成功了,非常感谢。我已经筋疲力尽了,我的大脑无法正常工作。
  • 您好@abbasalit987,如果这回答了您的问题,请将其标记为已接受,这会给您和回答者一些分数并提高声誉。
猜你喜欢
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
相关资源
最近更新 更多