Thread: Why would these be giving two different results though they point to the same place?

  1. #1
    cnoob()
    Join Date
    Mar 2015
    Posts
    28

    Why would these be giving two different results though they point to the same place?

    A bit confused per normal. Both of the isdigits should be pointing to the same place regardless if it's using [0] to call the array or [m] which is currently set to 0? Why would they be giving me different results? When I compile and run I get the following for the following inputs:

    if I put in 1 they both return 1
    if I put in 1andaword (isdigit(s[m])) returns a 0 but (isdigit(s[0])) returns a 1. same if I put 1 andawordwithaspacebetween?

    Code:
    int main (void) {
        int charcount = 0;
        int integers = 0;
        int integers2 = 0;
        int m = 0;
        char s[] = {0};
        int len = 0;
        printf("Enter a string:\n");
        scanf("%256[^\n]", s);
        len = strlen(s);
        if (isdigit(s[m])) {
           integers = integers + 1;
        }
        printf("there are %d integers in your string\n\n", integers);
        if (isdigit(s[0])) {
            integers2 = integers2 + 1;
        }
        printf("there are %d integers in your string", integers2);
        return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    This is likely wrong!

    Code:
    char s[] = {0};
    Try to allocate some space for your array.

    Like this which allocates 10 chars with the +1 for the ASCII NUL.

    Code:
    char s[10+1] = {0};
    Note: I would use a constant or a macro in place of the 10 in real code.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple Prefix Programming giving weird results
    By tmac619619 in forum C Programming
    Replies: 1
    Last Post: 03-13-2014, 08:18 PM
  2. Replies: 2
    Last Post: 04-27-2011, 04:34 AM
  3. Replies: 1
    Last Post: 04-03-2008, 01:17 AM
  4. Floating Point Exception Giving Me Trouble
    By IdioticCreation in forum C++ Programming
    Replies: 4
    Last Post: 02-10-2008, 07:31 PM
  5. Floating point faster than fixed-point
    By VirtualAce in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 11-08-2001, 11:34 PM