Thread: Returning pointers of arrays and representing boolarrays as other datatypes

  1. #1
    Registered User
    Join Date
    Feb 2019
    Posts
    69

    Returning pointers of arrays and representing boolarrays as other datatypes

    Hey,

    I know I do not need to return a pointer in this case, but I would like to understand it, that is why I do this.

    I have the following program:

    Code:
    #include "test.h"
    #include <stdlib.h>
    #include <stdbool.h>
    
    
    bool** getx(){
        bool* x[] = malloc(8); //create a char pointer represented by a pointer of bools...
        *x[0] = true;
        //do something...
        return x;
    }
    
    
    int main(int argv, char *args[]){
        bool** a = getx();
        printf("%s",(a)); //Return basically the char represented by the bools
        return 0;
    }
    So my question: how to create a pointer to an array of bools?

    Kind regards,
    Niclas

    P.S.: If your eyes are bleeding, please note that I am a beginner. In this case, it would nice if you would offer a solution to the problem and after this, you can tell me what you would do to not encounter the problem...

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You're making it more complex than it needs to be:
    Code:
    bool *x = malloc(number_of_bools * sizeof(x[0]));
    After checking that x is not a null pointer, you can say, assign true to x[i] where 0 <= i < number_of_bools, and return x from the function.
    Last edited by laserlight; 02-11-2019 at 03:38 PM.
    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

  3. #3
    Registered User
    Join Date
    Feb 2019
    Posts
    69
    How can you possibly initialize x with the size of x[0], which is not initialized yet?

    Code:
    #include "test.h"
    #include <stdlib.h>
    #include <stdbool.h>
    
    
    #include "test.h"
    #include <stdlib.h>
    #include <stdbool.h>
    
    
    
    
    bool* getx(){
        bool* x = malloc(8*sizeof(x[0])); //create a char pointer represented by a pointer of bools...
        x[0] = true;
        //do something...
        return x;
    }
    
    
    
    
    int main(int argv, char *args[]){
        bool* a = getx();
        printf("%s",(*a)); //Return basically the char represented by the bools
        return 0;
    }
    Last edited by SuchtyTV; 02-11-2019 at 03:42 PM.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You're not. You're allocating space for the number of bools you want, which means computing the number of bools you want * space for a bool such as x[0]. x is then initialised with a pointer to the memory allocated (or a null pointer otherwise).
    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

  5. #5
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <stdbool.h>
     
    bool *make_bool_array(int size) {
        bool *b = malloc(size * sizeof *b);
        if (!b) {
            perror("make_bool_array");
            exit(EXIT_FAILURE);
        }
        for (int i = 0; i < size; ++i)
            b[i] = false;
        return b;
    }
     
    void print_bool_array(bool *b, int size) {
        for (int i = 0; i < size; ++i)
            printf("%2d ", i);
        putchar('\n');
        for (int i = 0; i < size; ++i)
            printf(" %c ", b[i] ? 'T' : 'F');
        putchar('\n');
    }
     
    int main() {
        int size = 8;
        bool *b = make_bool_array(size);
        b[1] = b[4] = b[5] = true;
        print_bool_array(b, size);
        free(b);
        return 0;
    }
    A little inaccuracy saves tons of explanation. - H.H. Munro

  6. #6
    Registered User
    Join Date
    Feb 2019
    Posts
    69
    You're not. You're allocating space for the number of bools you want, which means computing the number of bools you want * space for a bool such as x[0]. x is then initialised with a pointer to the memory allocated (or a null pointer otherwise).
    Yes, you are right. I have not asked clearly:

    How do you initialize something using a property (not in the C# way) of the same something, if the same something is not initialized yet...


    Quote Originally Posted by john.c View Post
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <stdbool.h>
     
    bool *make_bool_array(int size) {
        bool *b = malloc(size * sizeof *b);
        if (!b) {
            perror("make_bool_array");
            exit(EXIT_FAILURE);
        }
        for (int i = 0; i < size; ++i)
            b[i] = false;
        return b;
    }
     
    void print_bool_array(bool *b, int size) {
        for (int i = 0; i < size; ++i)
            printf("%2d ", i);
        putchar('\n');
        for (int i = 0; i < size; ++i)
            printf(" %c ", b[i] ? 'T' : 'F');
        putchar('\n');
    }
     
    int main() {
        int size = 8;
        bool *b = make_bool_array(size);
        b[1] = b[4] = b[5] = true;
        print_bool_array(b, size);
        free(b);
        return 0;
    }
    1. Is there a way to read the bool array with ASCII - representation?
    2. Do you really need to free if you're leaving the process? If you forgot it, how to clean space?
    3. Same question here: How does the computer already know the sizeof b

    bool *b = malloc(size * sizeof *b);

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Oh, that's because (other than for variable length arrays), sizeof does not evaluate its operand, so you can use an operand in the midst of initialising it.
    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

  8. #8
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    sizeof just cares about the type of its argument. b[0] or *b are both of type bool, so it's the same as saying sizeof(bool). We prefer saying sizeof *b (or as laserlight prefers, sizeof b[0], presumably to emphasize to the reader that it's an array) because that way if we want to change the type we can do it in only one place.

    The OS will clean up the memory when the process ends, so you don't actually need to free the array. It's considered good practice, though.

    If you want to read and write your bools as chars then you can either just use chars in the first place or do the conversion. So if you are reading T's and F's from a file into a bool array you would need to convert:

    Example input file:
    Code:
    15
    T F F T F F F T F F T T T F F
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <stdbool.h>
     
    bool *read_bool_array(const char *filename, int *size) {
        FILE *fin = fopen(filename, "r");
        if (!fin) {
            perror("fopen");
            exit(EXIT_FAILURE);
        }
        fscanf(fin, "%d", size);
        bool *b = malloc(*size * sizeof *b);
        if (!b) {
            perror("malloc");
            exit(EXIT_FAILURE);  // OS will close file
        }
        for (int i = 0; i < *size; ++i) {
            char ch;
            fscanf(fin, " %c", &ch);  // the space before %c causes it to skip whitespace
            b[i] = (ch == 'T' || ch == 't');  // considering non-T's as F's
        }
        fclose(fin);
        return b;
    }
     
    void print_bool_array(const bool *b, int size) {
        for (int i = 0; i < size; ++i)
            printf("%2d ", i);
        putchar('\n');
        for (int i = 0; i < size; ++i)
            printf(" %c ", b[i] ? 'T' : 'F');
        putchar('\n');
    }
     
    int main() {
        int size;
        bool *b = read_bool_array("bools.txt", &size);
        print_bool_array(b, size);
        free(b);
        return 0;
    }
    Last edited by john.c; 02-11-2019 at 04:32 PM.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  9. #9
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Code:
        bool *b = malloc(*size * sizeof *b);
        if (!b) {
            perror("malloc");
            exit(EXIT_FAILURE);  // OS will close file
        }

    Just as a side note, you should avoid closing the programme on any error -
    Imagine if your customer has been working for 2hours entering data. Then all of the sudden "malloc" pops up on the screen and they lose all their work! You'll probably get an angry phone call and lose that customer.

    It is better to tell the user what is wrong (i.e. "Memory error" rather than "malloc"), and give them options before shutting down ("Try closing other programmes to free up some memory"), and then give them the option to retry or close the application
    Fact - Beethoven wrote his first symphony in C

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 10-01-2016, 05:28 AM
  2. Help with returning arrays using pointers
    By cuba06 in forum C Programming
    Replies: 9
    Last Post: 11-23-2007, 10:40 AM
  3. Returning Arrays as pointers
    By chinook86 in forum C Programming
    Replies: 7
    Last Post: 04-03-2007, 04:51 PM
  4. Replies: 2
    Last Post: 01-10-2005, 11:14 PM
  5. returning different datatypes
    By Wick in forum C++ Programming
    Replies: 7
    Last Post: 09-10-2003, 08:24 PM

Tags for this Thread