如何将char数组转换为int数组?
How to convert array of char into array of int?
#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 数组以执行一些数学运算。
你太努力了。类型转换应该是这样的
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};
.
中的小整数
#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 数组以执行一些数学运算。
你太努力了。类型转换应该是这样的
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};
.