结构体中有int *number成员。
想将字符串中的内容转化为数值进行保存,由于字符串是手动输入的,所以想通过malloc()函数来进行内存申请,这样做可以吗?如果可以的话,程序总是停止运行,又是为什么?
可以,你最好给出代码,判断可能是你的大小不正确,或者在函数内初始化指针,但是没有作用到调用函数的参数上
/*代码如下*/
void showNumbers(int *res, int count) {
int i;
for(i = count - 1; i >= 0; i--) {
printf(i == count - 1 ? "%d " : "%04d ", res[i]);
}
printf("\n");
}
int divideStringToGroups(char *str, int *res) {
char tmp[5] = {0};
int strLen;
int resLen;
int tmpIndex;
int strIndex;
int i;
strLen = strlen(str);
resLen = (str[0] == '-' || str[0] == '+' ? (strLen + 2)/4 : (strLen + 3)/4);
strIndex = strLen - 1;
res = (int *)calloc(sizeof(int), resLen);
for(i = 0; i < resLen; i++) {
if(strIndex >= strLen % 4) {
for(tmpIndex = 3; tmpIndex >= 0; tmpIndex--) {
tmp[tmpIndex] = str[strIndex--];
}
} else {
tmpIndex = 3;
if(isdigit(str[0]) || str[0] == '+') {
while(strIndex > 0) {
tmp[tmpIndex--] = str[strIndex--];
}
tmp[tmpIndex--] = str[0] == '+' ? '0' : str[strIndex--];
while(tmpIndex >= 0) {
tmp[tmpIndex--] = '0';
}
} else if(str[0] == '-') {
while(strIndex > 0) {
tmp[tmpIndex--] = str[strIndex--];
}
while(tmpIndex > 0) {
tmp[tmpIndex--] = '0';
}
tmp[0] = '-';
}
}
res[i] = atoi(tmp);
}
return resLen;
}
void main(void) {
char str[1000] = {0};
int *res = NULL;
int count;
gets(str);
count = divideStringToGroups(str, res);
showNumbers(res, count);
free(res);
}