So I wrote this program for class, compiled under Ubuntu using gcc 4.6.3, and for windows I compiled using mingw gcc 4.8.1, I have it working correctly and submitted, but I'm wondering why it isn't 100% in place portable as I would expect?
I'm having a for loop count differently on XP than it counts on Ubuntu, under xp I have to subtract one from count to get a correct count, under Ubuntu (as I would expect) I have to add one.
Here's the code, along with compile commands.
This one performs as expected on both OS's compiled and ran via a simple:Code:/* Reads from stdin and prints the c code to create a typedef struct header file * * @author Jeremy Jones * Course: COMS B25 * Created: Nov 7, 2013 * Source File: createStruct.c */ #include<stdio.h> #include<stdlib.h> int main(void) { char str1[1100][64], str2[1100][64]; double num[1100]; int numElem = 0; puts("typedef struct {"); puts("\tchar *sender, *reciever;"); puts("\tdouble amount;"); puts("} Transaction;"); puts(""); puts("Transaction transactions[] = {"); int i = 0; while ( EOF != scanf("%64s%64s%lf", str1[i], str2[i], &num[i]) ) { numElem = i + 1; i++; } for ( i = 0; i < (numElem - 1); i++ ) { printf("{\"%s\", \"%s\", %f},\n", str1[i], str2[i], num[i]); } printf("{\"%s\", \"%s\", %f}\n", str1[numElem - 1], str2[numElem - 1], num[numElem - 1]); puts("};"); }
Code:gcc createStruct.c -o createStruct ./createStruct < transactions.txt > transactions.hThis one counts the elements in the structure differently depending on os. Compiled and ranCode:/* Searches a structure for names and computes change * * @author Jeremy Jones * Course: COMS B25 * Created: Nov 7, 2013 * Source File: processTransactions.c */ #include "transactions.h" #include <stdio.h> #include <string.h> int main(void) { char name[64]; double netChange = 0; int count = 0; for (int i = 0; (transactions[i].reciever); ++i) { count = i + 1; // on windows I have to use i - 1 to get correct count } printf("Number of transactions = %d\n", count); printf("%s", "Enter name: "); scanf("%63s", name); for (int i = 0; i < count; i++) { if (!strcmp(name, transactions[i].sender)) { netChange -= transactions[i].amount; } else if (!strcmp(name, transactions[i].reciever)) { netChange += transactions[i].amount; } } printf("Net change for %s is %.2f\n", name, netChange); }
Any idea *why* they run differently? Is it something I'm doing?Code:gcc -std=c11 processTransactions.c -o processTransactions ./processTransactions
Bookmarks