Thread: Dynamically allocated array

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    20

    Dynamically allocated array

    i've dynamically allocated an array of two bytes and begun playing around with the bits.
    what i've wanted to do is have the program count how many 1s and 0s are in the memory allocated and print out the bits in the bytes. ive gotten it done so far with this:

    Code:
    #include "stdafx.h"
    #include "stdio.h"
    #include "stdlib.h"
    
    
    
    int main(int g, _TCHAR* argv[])
    {
    	int bitCount1 = 0;
    	int bitCount0 = 0;
    	char *ptr;
    	ptr = (char*)malloc(2);
    	
    for(int i=0; i < 2; ++i) {
    	for(int j=0; j < 8; ++j) {
    /* lowest bit is set, add to number of set bits */
    		if ((*ptr & 1) != 0)
    		{printf("%d", 1);
    		++bitCount1;}
    		else {(++bitCount0);
    		printf("%d", 0);}
    /* reduce value at ptr by power of 2 */
    *ptr >>= 1;
    }
    /* go to next byte addressed by ptr */
    ++ptr;
    }
    
    printf("\nThe number of ones in the memory allocated: %d\n", bitCount1);
    printf("The number of zeros in the memory allocated: %d\n", bitCount0);
    
    getchar();
    }
    the output right now is:

    1011001110110011
    The number of ones in the memory allocated: 10
    The number of zeros in the memory allocated: 6

    the only thing that bothers me is that both bytes have the same exact bit pattern of 10110011. the next thing i wanted to do was to find the hamming distance but it is clearly 0 in this situation.

    am i doing everything right here? is there a reason both bytes have the same bit pattern, i was expecting them to have completely different bit patterns since they are supposed to be different bytes. any help here?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Were you ever planning to, say, store something in these bytes? Or is the point to just grab whatever happened to be in that particular random memory location that you were allocated.

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    After a quick look, I don't see any reason why you would be looking at the same byte twice. As a test, try assigning different values to each byte after they're allocated to see. It's possible you're just getting 2 bytes that happen to contain the same value.

  4. #4
    Registered User
    Join Date
    Jun 2009
    Posts
    20
    Quote Originally Posted by tabstop View Post
    Were you ever planning to, say, store something in these bytes? Or is the point to just grab whatever happened to be in that particular random memory location that you were allocated.
    exactly that, just playing around with the bits/bytes that were randomly allocated

  5. #5
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305
    Quote Originally Posted by dre View Post
    i've dynamically allocated an array of two bytes and begun playing around with the bits.
    what i've wanted to do is have the program count how many 1s and 0s are in the memory allocated and print out the bits in the bytes. ive gotten it done so far with this:

    Code:
    #include "stdafx.h"
    #include "stdio.h"
    #include "stdlib.h"
    
    
    
    int main(int g, _TCHAR* argv[])
    {
    	int bitCount1 = 0;
    	int bitCount0 = 0;
    	char *ptr;
    	ptr = (char*)malloc(2);
    	
    for(int i=0; i < 2; ++i) {
    	for(int j=0; j < 8; ++j) {
    /* lowest bit is set, add to number of set bits */
    		if ((*ptr & 1) != 0)
    		{printf("%d", 1);
    		++bitCount1;}
    		else {(++bitCount0);
    		printf("%d", 0);}
    /* reduce value at ptr by power of 2 */
    *ptr >>= 1;
    }
    /* go to next byte addressed by ptr */
    ++ptr;
    }
    
    printf("\nThe number of ones in the memory allocated: %d\n", bitCount1);
    printf("The number of zeros in the memory allocated: %d\n", bitCount0);
    
    getchar();
    }
    the output right now is:

    1011001110110011
    The number of ones in the memory allocated: 10
    The number of zeros in the memory allocated: 6

    the only thing that bothers me is that both bytes have the same exact bit pattern of 10110011. the next thing i wanted to do was to find the hamming distance but it is clearly 0 in this situation.

    am i doing everything right here? is there a reason both bytes have the same bit pattern, i was expecting them to have completely different bit patterns since they are supposed to be different bytes. any help here?
    The program doesnt seem to compile. Also make sure that you do return 0 at the end of the main function.

    Just also what is the purpose of using stdafx.h

  6. #6
    Registered User
    Join Date
    Jun 2009
    Posts
    20
    Quote Originally Posted by roaan View Post
    The program doesnt seem to compile. Also make sure that you do return 0 at the end of the main function.
    Really? What are the errors? It's compiling and running fine for me.

  7. #7
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    One thing I notice is that you should be putting angle brackets < > around standard header files, not quotes.

  8. #8
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305
    Quote Originally Posted by dre View Post
    Really? What are the errors? It's compiling and running fine for me.
    First error that i get is the one below

    c:\documents and settings\rohan\my documents\visual studio 2008\projects\stringsds\stringsds\forum.c(1) : fatal error C1083: Cannot open include file: 'stdafx.h': No such file or directory


    Next when i comment that line i start getting a couple of other errors as well

    c:\documents and settings\rohan\my documents\visual studio 2008\projects\stringsds\stringsds\forum.c(7) : error C2143: syntax error : missing ')' before '*'

    c:\documents and settings\rohan\my documents\visual studio 2008\projects\stringsds\stringsds\forum.c(7) : error C2081: '_TCHAR' : name in formal parameter list illegal

    c:\documents and settings\rohan\my documents\visual studio 2008\projects\stringsds\stringsds\forum.c(7) : error C2143: syntax error : missing '{' before '*'

    c:\documents and settings\rohan\my documents\visual studio 2008\projects\stringsds\stringsds\forum.c(7) : error C2059: syntax error : ')'

    c:\documents and settings\rohan\my documents\visual studio 2008\projects\stringsds\stringsds\forum.c(8) : error C2054: expected '(' to follow 'argv'

    Build log was saved at "file://c:\Documents and Settings\ROHAN\My Documents\Visual Studio 2008\Projects\StringsDS\StringsDS\Debug\BuildLog.h tm"
    StringsDS - 5 error(s), 0 warning(s)

  9. #9
    Registered User
    Join Date
    Jun 2009
    Posts
    20
    Quote Originally Posted by roaan View Post
    First error that i get is the one below

    c:\documents and settings\rohan\my documents\visual studio 2008\projects\stringsds\stringsds\forum.c(1) : fatal error C1083: Cannot open include file: 'stdafx.h': No such file or directory


    Next when i comment that line i start getting a couple of other errors as well

    c:\documents and settings\rohan\my documents\visual studio 2008\projects\stringsds\stringsds\forum.c(7) : error C2143: syntax error : missing ')' before '*'

    c:\documents and settings\rohan\my documents\visual studio 2008\projects\stringsds\stringsds\forum.c(7) : error C2081: '_TCHAR' : name in formal parameter list illegal

    c:\documents and settings\rohan\my documents\visual studio 2008\projects\stringsds\stringsds\forum.c(7) : error C2143: syntax error : missing '{' before '*'

    c:\documents and settings\rohan\my documents\visual studio 2008\projects\stringsds\stringsds\forum.c(7) : error C2059: syntax error : ')'

    c:\documents and settings\rohan\my documents\visual studio 2008\projects\stringsds\stringsds\forum.c(8) : error C2054: expected '(' to follow 'argv'

    Build log was saved at "file://c:\Documents and Settings\ROHAN\My Documents\Visual Studio 2008\Projects\StringsDS\StringsDS\Debug\BuildLog.h tm"
    StringsDS - 5 error(s), 0 warning(s)
    weird...im using VS2005 and it works fine for me

  10. #10
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305
    I have no idea why this is happening. But if it works fine in vs2005 then it shoudl work perfectly with vs2008 as well.

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by dre
    weird...im using VS2005 and it works fine for me
    Make it easy for people to compile your code: get rid of the use of pre-compiled headers, and use only standard C unless something non-standard is necessary. With respect to C99, that would be:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        int bitCount1 = 0;
        int bitCount0 = 0;
        char *ptr;
        ptr = (char*)malloc(2);
    
        for(int i=0; i < 2; ++i) {
            for(int j=0; j < 8; ++j) {
                /* lowest bit is set, add to number of set bits */
                if ((*ptr & 1) != 0) {
                    printf("%d", 1);
                    ++bitCount1;
                } else {
                    (++bitCount0);
                    printf("%d", 0);
                }
                /* reduce value at ptr by power of 2 */
                *ptr >>= 1;
            }
            /* go to next byte addressed by ptr */
            ++ptr;
        }
    
        printf("\nThe number of ones in the memory allocated: %d\n", bitCount1);
        printf("The number of zeros in the memory allocated: %d\n", bitCount0);
    
        getchar();
    }
    Oh, and make it easy for people to read your code by indenting it reasonably and consistently.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #12
    Registered User
    Join Date
    Jun 2009
    Posts
    20
    so does anybody have some tips about my actual problem...does the logic look off to anyone or is everyone stumped about this like i am?

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    What is your actual problem?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    does the logic look off to anyone or is everyone stumped about this like i am?
    Did you try my suggestion from post #3? What happened?

  15. #15
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305
    Quote Originally Posted by laserlight View Post
    Make it easy for people to compile your code: get rid of the use of pre-compiled headers, and use only standard C unless something non-standard is necessary. With respect to C99, that would be:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        int bitCount1 = 0;
        int bitCount0 = 0;
        char *ptr;
        ptr = (char*)malloc(2);
    
        for(int i=0; i < 2; ++i) {
            for(int j=0; j < 8; ++j) {
                /* lowest bit is set, add to number of set bits */
                if ((*ptr & 1) != 0) {
                    printf("%d", 1);
                    ++bitCount1;
                } else {
                    (++bitCount0);
                    printf("%d", 0);
                }
                /* reduce value at ptr by power of 2 */
                *ptr >>= 1;
            }
            /* go to next byte addressed by ptr */
            ++ptr;
        }
    
        printf("\nThe number of ones in the memory allocated: %d\n", bitCount1);
        printf("The number of zeros in the memory allocated: %d\n", bitCount0);
    
        getchar();
    }
    Oh, and make it easy for people to read your code by indenting it reasonably and consistently.
    I had a few questions regarding the way the program was posted by the op

    ptr = (char*)malloc(2);

    Now this allocates 2 bytes in memory but ptr can hold the address of only the first byte as its a char pointer. So shouldnt it have been done like this

    ptr = (char*)malloc(sizeof(char));

    Besides when i try the program using this i get different bit patterns

    [insert]
    Code:
    # include <stdio.h>
    # include <stdlib.h>
    # include <string.h>
    
    
    int main(void)
    {
    	int i, j;
        int bitCount1 = 0;
        int bitCount0 = 0;
        char *ptr;
        ptr = (char*)malloc(sizeof(char));
    
        for(i=0; i < 2; i++) {
            for(j=0; j < 8; j++) {
                /* lowest bit is set, add to number of set bits */
                if ((*ptr & 1) != 0) {
                    printf("%d", 1);
                    ++bitCount1;
                } else {
                    (++bitCount0);
                    printf("%d", 0);
                }
                /* reduce value at ptr by power of 2 */
                *ptr >>= 1;
            }
            /* go to next byte addressed by ptr */
    		printf("\n");
            ++ptr;
        }
    
        printf("\nThe number of ones in the memory allocated: %d\n", bitCount1);
        printf("The number of zeros in the memory allocated: %d\n", bitCount0);
    
        getchar();
    
    }
    What is the reason behind that? It should have been the same as the previous case. Isnt it?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How To Declare and Dynamically Size a Global 2D Array?
    By groberts1980 in forum C Programming
    Replies: 26
    Last Post: 11-15-2006, 09:07 AM
  2. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM
  3. Destructors in dynamically allocated arrays
    By frenchfry164 in forum C++ Programming
    Replies: 1
    Last Post: 11-28-2003, 11:26 PM
  4. delete dynamically allocated char array
    By xddxogm3 in forum C++ Programming
    Replies: 7
    Last Post: 11-23-2003, 04:57 PM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM