當我嘗試從函數返回類型爲verylongint的值時,出現錯誤。什麼是正確的方式返回? verylongint是long long類型的數組,在第5行中定義。 返回verylongint的函數應該是string2verylongint(char * n)。編譯器的輸出低於源代碼。如何從函數返回一個定義的類型(數組)?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SIZE 63
typedef long long verylongint[63];
char* verylongint2string(verylongint n);
verylongint string2verylongint(char* n);
main(){
verylongint n;
int i;
for(i=0; i<SIZE; i++)n[i]=0; //initialize
n[0]= 999999999999999999;
n[1]= 999999999999999999;
n[2]= 2323232311;
printf("%s\n", verylongint2string(n));
verylongint m;
m = string2verylongint("123999999999999999999999999999999999999999999999999999999");
printf("%s\n", verylongint2string(m));
}
verylongint string2verylongint(char* n){
char m[18]; // first long long element, which is not zero, as string
sscanf(n, "%[^9]", m);
long long n1; // as long long
sscanf(m, "%lld", &n1);
int length= strlen(n)-strlen(m); // length of string without the first element
int i;
verylongint k; //return value
for(i=0; i<SIZE; i++)k[i]=0; //initialize
for(i=0; i<length/18; i++){ // length/18 is the number of elements (without 1st)
k[i]=999999999999999999;
}
k[i] = n1;
printf("%s\n", verylongint2string(k));
return k;
}
char* verylongint2string(verylongint n){
char* string = (char*) malloc(18*63*sizeof(char));//18 is the length of the biggest number
//63 is the length of the long-array
int i=SIZE;
while(n[--i]==0);
//string=n[i];
sprintf(string, "%lld", n[i]); //first number, which is not zero
while(--i>=0){ //adding the biggest number
strcat(string,"999999999999999999"); //the biggest number(one char smaller than lld)
}
return string;
}
輸出:
[email protected]:~/Documents$ gcc verylongint.c -o vli
verylongint.c:9:13: error: ‘string2verylongint’ declared as function returning an array
verylongint string2verylongint(char* n);
^
verylongint.c: In function ‘main’:
verylongint.c:21:4: error: incompatible types when assigning to type ‘verylongint’ from type ‘int’
m = string2verylongint("123999999999999999999999999999999999999999999999999999999");
^
verylongint.c: At top level:
verylongint.c:26:13: error: ‘string2verylongint’ declared as function returning an array
verylongint string2verylongint(char* n){
^
verylongint.c: In function ‘string2verylongint’:
verylongint.c:42:2: warning: return makes integer from pointer without a cast [enabled by default]
return k;
^
verylongint.c:42:2: warning: function returns address of local variable [-Wreturn-local-addr]
C函數不能按值返回數組。把它放到一個結構體中。 –
或決定誰(調用者或被調用者)將分配內存並使用指針 –
您需要學習使用C編程的第一件事是,99%的時間,調用者需要提供容器來展示結果,而不是返回容器與被調用者提供的結果。 – user3528438