使用ansi c
#define STDC_VERSION 201112L
我是c的新手,但我是Here的负责人
无论我尝试过哪种方法,都无法获得sum
指针来返回。
代码运行成功(创建正确的数字),并且printf
函数中的addNumericStrings
有效,但是printf
中的main
无效(不打印任何内容)。我假设由于错误而已。我在构建时没有收到任何警告。
输出
addNumericStrings.sum = 11234567889
主要
#include <stdio.h>
#include <stdlib.h>
#include "addViaStrings.h"
int main(void) {
char s1[] = "9999999999";
char s2[] = "1234567890";
char *sum = addNumericStrings(s1, s2);
printf("main.sum = %s\n", sum);
}
功能
#include <stdio.h>
#include <stdlib.h>
char addNumericStrings(char *s1, char *s2);
char leftPad(char *result, char *s, int maxlength);
int findMaxLength(char *s1, char *s2);
char addNumericStrings(char *s1, char *s2){
int maxlength = findMaxLength(s1, s2);
char addend1[maxlength];
char addend2[maxlength];
char *sum = (char *) malloc(sizeof(char) * (maxlength + 2) );
int a1, a2, total;
int carry = 0;
// char sum[(maxlength + 2)]; // +1 in case addition rolls over past maxlength
// Prepare the strings for manual addition
leftPad(addend1, s1, maxlength);
leftPad(addend2, s2, maxlength);
// Buffer sum with ascii zeros (#48), not 0, and not "\0"
for (int i = 0; i < (maxlength + 1); i++) { sum[i] = 48; }
sum[maxlength + 1] = 0;
// Run the manual addition
// Start adding individual ints from end (right side)
for (int i = maxlength - 1 ; i >= 0; i--) {
a1 = addend1[i] - '0'; // Convert to int
a2 = addend2[i] - '0'; // Convert to int
total = (a1 + a2 + carry);
carry = 0;
if ( total >= 10){
carry += 1;
total -= 10;
}
sum[i +1] = 48+total; // convert to ascii value for numbers (adding 48)
}
sum[0] = 48+carry; // add last carry to start of num always, even if 0
sum[maxlength + 1] = '\0';
printf("addNumericStrings.sum = %s\n", sum);
return sum;
}
char leftPad(char *result, char *s, int maxlength){
// Pads number to [000123456789]
( ...snip... )
}
int findMaxLength(char *s1, char *s2){
// Returns int value of the length of the longer between s1 and s2
int length1 = strlen(s1);
int length2 = strlen(s2);
int maxlength;
(length1 > length2) ? (maxlength = length1) : (maxlength = length2);
return maxlength;
}
答案 0 :(得分:1)
如果要从函数中返回char *
,则必须使用适当的返回类型:
char* foo(void)
// ^
{
char *bar;
// ...
return bar;
}