Jeśli musisz uwzględnić liczby ujemne, możesz potrzebować dodatkowej logiki. W rzeczywistości, gdy grasz z tablicami, nie wiesz, ile to jest z góry, możesz chcieć zrobić jeszcze więcej kontroli bezpieczeństwa, a dodanie API do obsługi struktury danych jest bardzo wygodne.
// returns the number of digits converted
// stores the digits in reverse order (smalles digit first)
// precondition: outputdigits is big enough to store all digits.
//
int convert(int number, int* outputdigits, int* signdigit) {
int* workingdigits = outputdigits;
int sign = 1;
if(number < 0) { *signdigit = -1; number *= -1; }
++workingdigits;
for (; number > 0; ++ workingdigits) {
*workingdigits = number % 10;
number = number/10;
}
return workingdigits - outputdigits;
}
void printdigits(int* digits, int size, int signdigit) {
if(signdigit < 0) printf("-");
for(int* digit = digits+size-1; digit >= digits; --digit){
printf("%d", *digit);
}
}
int main() {
int digits[10];
int signdigit;
printdigits(digits, convert(10, digits, &signdigit), signdigit);
printdigits(digits, convert(-10, digits, &signdigit), signdigit);
printdigits(digits, convert(1005, digits, &signdigit), signdigit);
}
dlaczego ta funkcja jest wskaźnikiem char? A co robi nowy char [długość]? Wygląda jak wskaźnik do pierwszego indeksu tablicy, ale mój kompilator nie ma ochoty "nowy znak" – droseman
"nowy znak" to C++. Właściwym sposobem zrobienia tego w C jest drugi bit kodu. –
Ponadto ważne jest, aby na końcu programu wywoływać funkcję 'free()' na macierzy, którą otrzymałeś z tej funkcji. W przeciwnym razie tracisz pamięć. –