[英]C char** get result
I want to get result by char **
, but the result is only one char, why?我想通过
char **
得到结果,但结果只有一个字符,为什么? I don't want to use return char *
to solve this question.我不想用
return char *
来解决这个问题。 who can tell me?谁能告诉我?
void test() {
char A[] = "123,563";
char *result = (char *)malloc(5*sizeof(char));
addStringAtoB(A, &result);
printf("\n result :----- %s \n", result); // result is not all, but one point ?
}
int addStringAtoB(char string[], char **result) {
char* token = strtok( string, ",");
char *stringA;
if (token != NULL) {
stringA = token;
token = strtok( NULL, ",");
}
char *stringB;
if (token != NULL) {
stringB = token;
}
int lenA = strlen(stringA);
int lenB = strlen(stringB);
int len = lenA < lenB ? lenA : lenB;
char resultTem[1000] = {};
for (int i=0; i<len; i++) {
char a = stringA[i];
char b = stringB[i];
if (a >='0' && a <= '9' && b >='0' && b <= '9') {
int c = (int)(a - '0') + (int)(b - '0');
resultTem[i] = c + '0';
}
else {
*result = "error";
return 0;
}
}
if (len == lenA) {
for (int j=len; j<lenB; j++) {
resultTem[j] = stringB[j];
}
}
else if (len == lenB) {
for (int j=len; j<lenA; j++) {
resultTem[j] = stringA[j];
}
}
**result = *resultTem;
return 0;
}
Your question is not clear and it is not well defined.你的问题不清楚,也没有很好的定义。
I arranged a little bit your code in a way that I consider it could be sufficient to answer to your question.我以一种我认为足以回答您的问题的方式安排了您的代码。 Anyway, I left to you the correctness controls of your code.
不管怎样,我把代码的正确性控制留给了你。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int addStringAtoB(char string[], char **result) {
char* token = strtok( string, ",");
char *stringA;
if (token != NULL) {
stringA = token;
token = strtok( NULL, ",");
}
char *stringB;
if (token != NULL) {
stringB = token;
}
int lenA = strlen(stringA);
int lenB = strlen(stringB);
int len = lenA < lenB ? lenA : lenB;
char resultTem[1000] = {};
int i=0;
for (; i<len; i++) {
char a = stringA[i];
char b = stringB[i];
if (a >='0' && a <= '9' && b >='0' && b <= '9') {
int c = (int)(a - '0') + (int)(b - '0');
resultTem[i] = c + '0';
}
else {
*result = "error";
return 0;
}
}
if (len == lenA) {
int j=len;
for (; j<lenB; j++) {
resultTem[j] = stringB[j];
}
}
else if (len == lenB) {
int j=len;
for (; j<lenA; j++) {
resultTem[j] = stringA[j];
}
}
*result = resultTem;
return 0;
}
int main() {
char A[] = "123,563";
char *result = (char *)malloc(5*sizeof(char));
(void)addStringAtoB(A, &result);
printf("\n result :----- %s \n", result); // result is not all, but one point ?
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.