I have a problem with an "add calculator".
Valgrind reports no memory errors, no errors from compiler but the program doesn't show any output despite the printf - "Base is ".
All pointers, and variables are (n my opinion) correctly initialized.
getnum function gets a number, returns a pointer to char - char *,
add function processes two numbers as strings, returns result which is a pointer to char (char *) as well.
I don't know whether the problem is memory allocation or procedures connected to processing arrays...
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX(A,B) ((A)>(B) ? (A) : (B))
char *getnum(FILE *infile, int base)
{
int len = 10;
int c;
int pos = 0;
char *num = NULL;
char *tmpnum = NULL;
num = malloc(sizeof(char)*len);
while (((c = fgetc(infile)) != EOF) && (isalnum(c))) {
if (isdigit(c)) {
/* irrelevant*/
}
else if (isalpha(c)) {
fprintf(stderr, "Wrong base, expected 16\n");
free(num);
return NULL;
}
if (pos >= len) {
/*realloc*/
}
}
return num;
}
int main(int argc, char **argv)
{
FILE *infile = NULL;
char *number1 = NULL;
char *number2 = NULL;
char *result = NULL;
int base, i, j = 0, length, count = 0;
infile = fopen(argv[1], "r");
base = atoi(argv[2]);
while (!feof(infile)) {
number1 = getnum(infile, base);
number2 = getnum(infile, base);
break;
}
printf("Base is %d\n", base);
result = add(number1, number2, base);
length = strlen(result);
for (i = 0; i <= length - 1; i++) {
if (result[i] == '0') {
count++;
}
}
for (j = i; j == (length - 1); j++) {
printf("Result is: %s\n", &result[j]);
break;
}
free(result);
result = NULL;
fclose(infile);
return 0;
}
Trying to work it out for the past 4 hours and can't find a mistake.
Thanks in advance!
There is one severe typo near the end of main().
for (j = i; j == (length - 1); j++) {
/* ^^ SHOULD BE <= */
printf("Result is: %s\n", &result[j]);
break;
}
Looking at this code:
for (i = 0; i <= length - 1; i++) {
if (result[i] == '0') {
count++;
}
}
if (count == length) {
printf("Result is 0\n");
free(result);
result = NULL; /* arguable */
fclose(infile);
return 0;
}
for (i = 0; i <= length - 1; i++) {
if (result[i] != '0') {
break;
}
}
for (j = i; j == (length - 1); j++) {
printf("Result is: %s\n", &result[j]);
break;
}
Instead of counting the total number of zeroes in the output number, and then counting the number of leading zeroes again, why not combine the two?
What is the last loop about? It's not even really a loop - it will execute once if i is length - 1, or not at all if not (presumably you're hitting the latter case in your test input).
e.g.
for (count = 0; count < length; count++) {
if (result[count] != '0')
break;
}
if (count == length) {
printf("Result is 0\n");
free(result);
result = NULL; /* arguable */
fclose(infile);
return 0;
}
printf("Result is: %s\n", &result[count]);
Related
I'm trying to count chars from input, and I noticed that while(getchar()!=EOF) produces an extra count, Is it because it counts the null-terminated from input?
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define LINE 5
#define MEM_SIZE 10
char *getInput(int *counter);
void printInput(char *input);
int main() {
char *mainInput;
int counter = 0;
printf("Please enter your input:\n");
mainInput = getInput(&counter);
if (mainInput == NULL) {
return 1;
}
printf("\n\n\nOutput:\n%s\n", mainInput);
printf("number of chars: %d\n", counter);
printInput(mainInput);
free(mainInput);
return 0;
}
char *getInput(int *counter) {
char *p = (char *)malloc(MEM_SIZE * sizeof(char));
char *q = p; /* backup pointer, if realloc fails to allocate, function will return last address values stored */
int c;
int temp_counter = 0;
long current = 0, last = MEM_SIZE - 1;
while ((c = getchar()) != EOF) {
if (current >= last) {
q = p;
p = (char *)realloc(q, last + (MEM_SIZE * sizeof(char)));
if (p == NULL) {
printf("Memory allocation failed, printing only stored values \n");
return q;
}
last += MEM_SIZE;
}
p[current] = c;
temp_counter++;
printf("number of chars: %d\n", temp_counter);
++current;
}
p[current] = '\0';
(*counter) = temp_counter - 1;
return p;
}
void printInput(char *input) {
int i, j = 0;
while (input[j] != '\0') {
for (i = 0; i < LINE; i++) {
if (input[j] == '\0')
break;
putchar(input[j]);
++j;
}
if (input[j] != '\0')
putchar('\n');
}
}
I'm stuck on an assignment I have to read from console really long number and then print it out using char* arr. Then I need to add and subtract number 1 array to number2 array. To be honest adding and subtracting I will probably deal on my own but I cannot figure out how to read those input characters, character by character and make while break after enter in console.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int subtract(const char* number1, const char* number2, char** result){
if(number1 == NULL || number2 == NULL){
return 1;
}
return 0;
}
int add(const char* number1, const char* number2, char** result) {
if(number1 == NULL || number2 == NULL){
return 1;
}
return 0;
}
int input_check(int check, char* number) {
if (check != 1) {
return 1;
}
else {
return 0;
}
}
int main()
{
char* number1;
//char* number2;
//char** result;
int check = 0;
number1 = (char*)calloc(200,sizeof(char));
//number2 = (char*)calloc(200, sizeof(char));
//result = (char*)malloc(sizeof(char) * sizeof(char) * 400);
if (number1 == NULL) {
printf("Failed to allocate memory");
return 8;
}
printf("Input first num: ");
int i = 0;
while (1) {
char retVal;
scanf("%c", &retVal);
if (retVal >= 48 || retVal <= 57 || retVal != '\0') {
*(number1 + i) = retVal;
if ((number1 + i) == NULL) {
break;
}
printf("%d", atoi((number1 + i)));
i++;
}
else
{
break;
}
}
return 0;
}
Thanks for any help
As there is no limit on the numbers, you need to use dynamic memory allocation.
The straightforward (brute-force) way is to keep increasing the allocated size
char *input = calloc(1, 1); // space for '\0'
size_t len = 0;
for (;;) {
int ch = getchar();
if (ch != '\n') {
input[len] = ch; // replace '\0' with ch
len++;
char *tmp = realloc(input, len + 1);
if (tmp == NULL) exit(EXIT_FAILURE);
input = tmp;
input[len] = 0; // add '\0'
} else {
break;
}
}
// use input and len
free(input);
Sort command of linux must sort the lines of a text file and transfer the output to another file. But my code gives a runtime error. Please rectify the pointer mistakes so that output.
In which line exactly should I make changes? Because there is no output after all.
I'm pasting the whole code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sortfile(char **arr, int linecount) {
int i, j;
char t[500];
for (i = 1; i < linecount; i++) {
for (j = 1; j < linecount; j++) {
if (strcmp(arr[j - 1], arr[j]) > 0) {
strcpy(t, arr[j - 1]);
strcpy(arr[j - 1], arr[j]);
strcpy(arr[j], t);
}
}
}
}
int main() {
FILE *fileIN, *fileOUT;
fileIN = fopen("test1.txt", "r");
unsigned long int linecount = 0;
int c;
if (fileIN == NULL) {
fclose(fileIN);
return 0;
}
while ((c = fgetc(fileIN)) != EOF) {
if (c == '\n')
linecount++;
}
printf("line count=%d", linecount);
char *arr[linecount];
char singleline[500];
int i = 0;
while (fgets(singleline, 500, fileIN) != NULL) {
arr[i] = (char*)malloc(500);
strcpy(arr[i], singleline);
i++;
}
sortfile(arr, linecount);
for (i = 0; i < linecount; i++) {
printf("%s\n", arr[i]);
}
fileOUT = fopen("out.txt", "w");
if (!fileOUT) {
exit(-1);
}
for (i = 0; i < linecount; i++) {
fprintf(fileOUT, "%s", arr[i]);
}
fclose(fileIN);
fclose(fileOUT);
}
The problem in your code is you do not rewind the input stream after reading it the first time to count the number of newlines. You should add rewind(fileIN); before the next loop.
Note however that there are other problems in this code:
the number of newline characters may be less than the number of successful calls to fgets(): lines longer than 499 bytes will be silently broken in multiple chunks, causing more items to be read by fgets() than newlines. Also the last line might not end with a newline. Just count the number of successful calls to fgets().
You allocate 500 bytes for each line, which is potentially very wasteful. Use strdup() to allocate only the necessary size.
Swapping the lines in the sort routine should be done by swapping the pointers, not copying the contents.
allocating arr with malloc is safer and more portable than defining it as a variable sized array with char *arr[linecount];
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sortfile(char **arr, int linecount) {
for (;;) {
int swapped = 0;
for (int j = 1; j < linecount; j++) {
if (strcmp(arr[j - 1], arr[j]) > 0) {
char *t = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = t;
swapped = 1;
}
}
if (swapped == 0)
break;
}
}
int main() {
FILE *fileIN, *fileOUT;
char singleline[500];
int i, linecount;
fileIN = fopen("test1.txt", "r");
if (fileIN == NULL) {
fprintf(stderr, "cannot open %s\n", "test1.txt");
return 1;
}
linecount = 0;
while (fgets(singleline, 500, fileIN)) {
linecount++;
}
printf("line count=%d\n", linecount);
char **arr = malloc(sizeof(*arr) * linecount);
if (arr == NULL) {
fprintf(stderr, "memory allocation failure\n");
return 1;
}
rewind(fileIN);
for (i = 0; i < linecount && fgets(singleline, 500, fileIN) != NULL; i++) {
arr[i] = strdup(singleline);
if (arr[i] == NULL) {
fprintf(stderr, "memory allocation failure\n");
return 1;
}
}
fclose(fileIN);
if (i != linecount) {
fprintf(stderr, "line count mismatch: i=%d, lilnecount=%d\n",
i, linecount);
linecount = i;
}
sortfile(arr, linecount);
for (i = 0; i < linecount; i++) {
printf("%s", arr[i]);
}
fileOUT = fopen("out.txt", "w");
if (!fileOUT) {
fprintf(stderr, "cannot open %s\n", "out.txt");
return 1;
}
for (i = 0; i < linecount; i++) {
fprintf(fileOUT, "%s", arr[i]);
}
fclose(fileOUT);
for (i = 0; i < linecount; i++) {
free(arr[i]);
}
free(arr);
return 0;
}
To get a different sort order, you would change the comparison function. Instead of strcmp() you could use this:
#include <ctype.h>
int my_strcmp(const char *s1, const char *s2) {
/* compare strings lexicographically but swap lower and uppercase letters */
unsigned char c, d;
while ((c = *s1++) == (d = *s2++)) {
if (c == '\0')
return 0; /* string are equal */
}
/* transpose case of c */
if (islower(c)) {
c = toupper(c);
} else {
c = tolower(c);
}
/* transpose case of d */
if (islower(d)) {
d = toupper(d);
} else {
d = tolower(d);
}
/* on ASCII systems, we should still have c != d */
/* return comparison result */
if (c <= d)
return -1;
} else {
return 1;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I was trying to solve CountAndSay problem at one of the online coding site but I am not able to get why my program is printing NULL. I am sure I am doing some conceptual mistake but not getting it.
Here is my code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* countAndSay(int A) {
int i,j,k,f,count;
char a;
char *c = (char*)malloc(sizeof(char)*100);
char *temp = (char*)malloc(sizeof(char)*100);
c[0] = 1;c[1] = '\0';
for(k=2; k<=A; k++)
{
for(i=0, j=0; i<strlen(c); i++)
{
a = c[i];
count = 1;
i++;
while(c[i] != '\0')
{
if(c[i]==a)
{
count++;
i++;
}
else if(c[i] != a)
{
i--;
break;
}
else
{
break;
}
}
temp[j] = count;
temp[j+1] = a;
j += 2;
}
*(temp+j) = '\0';
if(k<A)
{
for(j=0; j<strlen(temp); j++)
{
c[j] = temp[j];
}
c[j] = '\0';
}
}
return temp;
}
int main(void) {
// your code goes here
char *c = countAndSay(8);
printf("%s\n",c);
return 0;
}
The idea is not that bad, the main errors are the mix-up of numerical digits and characters as shown in the comments.
Also: if you use dynamic memory, than use dynamic memory. If you only want to use a fixed small amount you should use the stack instead, e.g.: c[100], but that came up in the comments, too. You also need only one piece of memory. Here is a working example based on your code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// ALL CHECKS OMMITTED!
char *countAndSay(int A)
{
int k, count, j;
// "i" gets compared against the output of
// strlen() which is of type size_t
size_t i;
char a;
// Seed needs two bytes of memory
char *c = malloc(2);
// Another pointer, pointing to the same memory later.
// Set to NULL to avoid an extra malloc()
char *temp = NULL;
// a temporary pointer needed for realloc()-ing
char *cp;
// fill c with seed
c[0] = '1';
c[1] = '\0';
if (A == 1) {
return c;
}
// assuming 1-based input, that is: the first
// entry of the sequence is numbered 1 (one)
for (k = 2; k <= A; k++) {
// Memory needed is twice the size of
// the former entry at most.
// (Averages to Conway's constant but that
// number is not usable here, it is only a limit)
cp = realloc(temp, strlen(c) * 2 + 1);
temp = cp;
for (i = 0, j = 0; i < strlen(c); i++) {
//printf("A i = %zu, j = %zu\n",i,j);
a = c[i];
count = 1;
i++;
while (c[i] != '\0') {
if (c[i] == a) {
count++;
i++;
} else {
i--;
break;
}
}
temp[j++] = count + '0';
temp[j++] = a;
//printf("B i = %zu, j = %zu\n",i,j-1)
//printf("B i = %zu, j = %zu\n",i,j);
}
temp[j] = '\0';
if (k < A) {
// Just point "c" to the new sequence in "temp".
// Why does this work and temp doesn't overwrite c later?
// Or does it *not* always work and fails at one point?
// A mystery! Try to find it out! Some hints in the code.
c = temp;
temp = NULL;
}
// intermediate results:
//printf("%s\n\n",c);
}
return temp;
}
int main(int argc, char **argv)
{
// your code goes here
char *c = countAndSay(atoi(argv[1]));
printf("%s\n", c);
free(c);
return 0;
}
To get a way to check for sequences not in the list over at OEIS, I rummaged around in my attic and found this little "gem":
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
char *conway(char *s)
{
char *seq;
char c;
size_t len, count, i = 0;
len = strlen(s);
/*
* Worst case is twice as large as the input, e.g.:
* 1 -> 11
* 21 -> 1211
*/
seq = malloc(len * 2 + 1);
if (seq == NULL) {
return NULL;
}
while (len) {
// counter for occurrences of ...
count = 0;
// ... this character
c = s[0];
// as long as the string "s"
while (*s != '\0' && *s == c) {
// move pointer to next character
s++;
// increment counter
count++;
// decrement the length of the string
len--;
}
// to keep it simple, fail if c > 9
// but that cannot happen with a seed of 1
// which is used here.
// For other seeds it might be necessary to
// use a map with the higher digits as characters.
// If it is not possible to fit it into a
// character, the approach with a C-string is
// obviously not reasonable anymore.
if (count > 9) {
free(seq);
return NULL;
}
// append counter as a character
seq[i++] = (char) (count + '0');
// append character "c" from above
seq[i++] = c;
}
// return a proper C-string
seq[i] = '\0';
return seq;
}
int main(int argc, char **argv)
{
long i, n;
char *seq0, *seq1;
if (argc != 2) {
fprintf(stderr, "Usage: %s n>0\n", argv[0]);
exit(EXIT_FAILURE);
}
// reset errno, just in case
errno = 0;
// get amount from commandline
n = strtol(argv[1], NULL, 0);
if ((errno == ERANGE && (n == LONG_MAX || n == LONG_MIN))
|| (errno != 0 && n == 0)) {
fprintf(stderr, "strtol failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (n <= 0) {
fprintf(stderr, "Usage: %s n>0\n", argv[0]);
exit(EXIT_FAILURE);
}
// allocate space for seed value "1" plus '\0'
// If the seed is changed the limit in the conway() function
// above might need a change.
seq0 = malloc(2);
if (seq0 == NULL) {
fprintf(stderr, "malloc() failed to allocate a measly 2 bytes!?\n");
exit(EXIT_FAILURE);
}
// put the initial value into the freshly allocated memory
strcpy(seq0, "1");
// print it, nicely formatted
/*
* putc('1', stdout);
* if (n == 1) {
* putc('\n', stdout);
* free(seq0);
* exit(EXIT_SUCCESS);
* } else {
* printf(", ");
* }
*/
if (n == 1) {
puts("1");
free(seq0);
exit(EXIT_SUCCESS);
}
// adjust count
n--;
for (i = 0; i < n; i++) {
// compute conway sequence as a recursion
seq1 = conway(seq0);
if (seq1 == NULL) {
fprintf(stderr, "conway() failed, probably because malloc() failed\n");
exit(EXIT_FAILURE);
}
// make room
free(seq0);
seq0 = NULL;
// print sequence, comma separated
// printf("%s%s", seq1, (i < n - 1) ? "," : "\n");
// or print sequence and length of sequence, line separated
// printf("%zu: %s%s", strlen(seq1), seq1, (i < n-1) ? "\n\n" : "\n");
// print the endresult only
if (i == n - 1) {
printf("%s\n", seq1);
}
// reuse seq0
seq0 = seq1;
// not necessary but deemed good style by some
// although frowned upon by others
seq1 = NULL;
}
// free the last memory
free(seq0);
exit(EXIT_SUCCESS);
}
I have a problem at the add2_recur function. I am trying to add up a single character digit within a string. But I do not know how to return a string to my main function so I can print out the result. I try using function pointer but i only return the first value of the string.
Any suggestion on how to do this would be helpful.
//check if string is valid
int digcheck_helper(char *theno, int start, int length) {
int charToInt = *(theno+start);
if(!((charToInt >= 48) &&(charToInt <= 57)))
return 0;
if(length == 0)
return 1;
return digcheck_helper(theno,start+1,length-1);
}
int digcheck(char *str, int start, int length) {
return digcheck_helper(string,start,length);
}
/**********************
****add recursive function**/
void add2_recur(char *num1, char *num2, int start, int carryDig) {
int singleChar1 = *(num1 + start), singleChar2 = *(num2 + start);
char *str = (char*) malloc(strlen(num1) + 2);
sum = singleChar1 + singleChar - 96;
if(carryDig == 1)
sum = sum + 1;
if(start < strlen(num1)) {
if(sum >= 10) {
sum = sum - 10;
str[start] = sum + 48;
carryDig = 1;
printf("sum of single digit is: %c\n", str[start]);
}
else if( sum < 10) {
str[start] = sum + 48;
carryDig = 0;
printf("sum of single digit is: %c\n", str[start]);
}
add2_recur(num1,num2,start+1,carryDig);
}
else if ((start == strlen(num1)) && (carryDig ==1)){
str[start+1] = 48;
printf("sum of single digit is: %c\n", str[start+1]);
}
}
void add2(char *n1, char *n2) {
add2_recur(n1,n2,0,0)
}
/*******************/
int main() {
char string1[20000], string2[20000], revStr1[20000], revStr2[20000];
int digit_1, digit_2, i;
printf("Enter first number >");
fgets(string1,20000,stdin);
string1[strlen(string1)-1] = '\0';
digit_1 = digcheck(string1,0,strlen(string1)-1);
//Check if string is valid integer
if(digit_1 = 0)
printf("This number is invalid\n");
else{
printf("Enter second number >");
fgets(string2,2000,stdin);
string2[strlen(string2)-1] = '\0';
digit_2 = digcheck(string2,0,strlen(string2-1);
if(digit_2 == 0)
printf("This number is invalid\n");
else
printf("1st num is %s\n2st num is %s\n", string1, string2);
}
// reverse string
for(i=0;i<strlen(string1);i++)
revStr1[i] = string1[(strlen(string1)-1) - i];
for(i=0;i,strlen(string2);i++)
revStr2[i] = string2[(strlen(string2) -1) - i];
// compare string and pass to add2
if(strlen(revStr1) < strlen(revStr2)) {
for(i = strlen(revStr1); i < strlen(revStr2); i++)
revStr1[i] = '0';
add2(revStr1,revStr2);
}
else if(strlen(revStr2) < strlen(revStr1)) {
for(i = strlen(revStr2); i < strlen(revStr1); i++)
revStr2[i] = '0';
add2(revStr1,revStr2);
}
else
add2(revStr1,revStr2);
return 0;
}
In C something like this is typically achieved by not returning the actual string. Instead you can just work with a pointer to a buffer passed to you. Use the actual return value to report status messages instead.
To not spoil the actual task for you, let's define a simple recursive function that will return a string with all non-alphanumerical characters being stripped:
#include <stdio.h>
#include <string.h>
int strip_stuff_rec(const char *input, char *output, unsigned int offset_input, unsigned offset_output) {
// Retrieve the character and move the offset
const char c = input[offset_input++];
if (c == '\0') { // Terminator; we're done!
// Terminate the output string
output[offset_output] = '\0';
return 1; // Signal success
}
// Character is alphanumeric?
if (isalnum(c)) {
// Append the character to our result and move the offset
output[offset_output++] = c;
}
// To have an error case, let's just pretend the string must not include #!
if (c == '#') {
return 0; // Signal an error
}
// Now handle the next position
return strip_stuff_rec(input, output, offset_input, offset_output);
}
int strip_stuff(const char *input, char *output) {
// Reset the output
output[0] = '\0';
// Start the recursive calls
return strip_stuff_rec(input, output, 0, 0);
}
int main(int argc, char **argv) {
// First let's set some input string
const char *input = "Hello World! -- I've had a wonderful day!";
// And we'll need a buffer for our result
char result[256];
// Now call the function and check the return value to determine
// whether it's been successful.
if (strip_stuff(input, result) == 0) {
printf("Some error happened!\n");
}
else {
printf("The stripped string is '%s'.\n", result);
}
}
this function:
void add2(char *n1, char *n2)
{
add2_recur(n1,n2,0,0)
}
this function has a couple of problems.
1) it will not compile because the statement that calls add2-recur()
is missing a trailing ';'
2) this function is not needed as add2_recur can be called directly
3) this is expected to add two numbers together ..
How is it to return the result?
It (probably) should be more like:
void add2(char *n1, char *n2, char *sum)
{
strcpy(sum, add2_recur(n1,n2,0,0) );
}
ok, i fix the code by creating a pointer function and storing the value into the str array by using malloc. I commented out the code. But it still only return the first element of the array to the main function from the heap. How do i get it to return the whole array?
//check if string is valid
int digcheck_helper(char *theno, int start, int length) {
int charToInt = *(theno+start);
if(!((charToInt >= 48) &&(charToInt <= 57)))
return 0;
if(length == 0)
return 1;
return digcheck_helper(theno,start+1,length-1);
}
int digcheck(char *str, int start, int length) {
return digcheck_helper(string,start,length);
}
/**********************
****add recursive function**/
char *add2_recur(char *num1, char *num2, int start, int carryDig) {
int singleChar1 = *(num1 + start), singleChar2 = *(num2 + start);
char *str = (char*) malloc(strlen(num1) + 2), sum;
sum = singleChar1 + singleChar - 96;
if(carryDig == 1)
sum = sum + 1;
if(start < strlen(num1)) {
if(sum >= 10) {
sum = sum - 10;
str[start] = sum + 48; //store value in each element of an array
carryDig = 1;
printf("sum of single digit is: %c\n", str[start]);
}
else if( sum < 10) {
str[start] = sum + 48; //store value in each element of an array
carryDig = 0;
printf("sum of single digit is: %c\n", str[start]);
}
add2_recur(num1,num2,start+1,carryDig);
}
else if ((start == strlen(num1)) && (carryDig ==1)){
str[start+1] = 49; // store value in each element of an array
printf("sum of single digit is: %c\n", str[start+1]);
}
return str;
}
/*******************/
int main() {
char string1[20000], string2[20000], revStr1[20000], revStr2[20000], *addResult;
int digit_1, digit_2, i;
printf("Enter first number >");
fgets(string1,20000,stdin);
string1[strlen(string1)-1] = '\0';
digit_1 = digcheck(string1,0,strlen(string1)-1);
//Check if string is valid integer
if(digit_1 = 0)
printf("This number is invalid\n");
else{
printf("Enter second number >");
fgets(string2,2000,stdin);
string2[strlen(string2)-1] = '\0';
digit_2 = digcheck(string2,0,strlen(string2-1);
if(digit_2 == 0)
printf("This number is invalid\n");
else
printf("1st num is %s\n2st num is %s\n", string1, string2);
}
// reverse string
for(i=0;i<strlen(string1);i++)
revStr1[i] = string1[(strlen(string1)-1) - i];
for(i=0;i,strlen(string2);i++)
revStr2[i] = string2[(strlen(string2) -1) - i];
// compare string and pass to add2
if(strlen(revStr1) < strlen(revStr2)) {
for(i = strlen(revStr1); i < strlen(revStr2); i++)
revStr1[i] = '0';
add2(revStr1,revStr2);
}
else if(strlen(revStr2) < strlen(revStr1)) {
for(i = strlen(revStr2); i < strlen(revStr1); i++)
revStr2[i] = '0';
addResult = add2(revStr1,revStr2);
}
else
addResult = add2(revStr1,revStr2);
// print out
printf("sum is: %s\n", addResult);
return 0;
Since passing the whole array is not very optimal, C usually in most of the expressions convert it to pointer.
One way to pass whole array is by enclosing it in a struct. (Not a good solution though)
typedef struct
{
char s[128];
}MYSTR;