Thread: A weird question

  1. #1
    Registered User
    Join Date
    Oct 2019
    Posts
    34

    A weird question

    Is there any way to declare an array inside main function but initialization of this array will be into another function (out of main function)?. If possible, after initialization, is there any possibility to use those initialized data inside main function. I made the following program. However I was unable to run.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    struct sample
    {
    public:
    	void func(double *arrD)
    	{
    		int length = 3;
    		double testData[3] = { 3, 7, 6 };
    		arrD = (double*)malloc(length * sizeof(double));
    		for (int i = 0; i < length; i++)
    				arrD[i] = testData[i];
    	}
    };
    
    
    
    
    int main()
    {
    	struct sample sam1;
    	double* arr = nullptr;
    	sam1.func(arr);
    
    
    		for (int i = 0; i < 3; i++)
    			printf("	%d \n", arr[i]);
    
    
    	return 0;
    }
    Last edited by Shafiul; 10-17-2020 at 02:19 PM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,082
    If you're talking about initialisation in the strict sense of the term, then no: you must initialise at the point of declaration.

    However, it looks like you're talking about initialisation more loosely in the sense of providing a useful initial value. The answer of course is yes: you were close, just that you don't need the malloc because you already have storage allocated, i.e., the array itself, and in main you need to declare the array, not a pointer.

    By the way, you posted this in the C programming forum, but it looks like C++ written in a C style. Shall I move this to the C++ programming forum, or was the class definition a mistake?
    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 rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    750
    This forum is for the discussion of C not C++. You should post in the C++ forum.

  4. #4
    Registered User
    Join Date
    Oct 2019
    Posts
    34
    Hi Amanda, Nice to see your feed back. I wrote a sample program for one test case. However, for some reason, I can not declare the array or allocate a pointer with a specific size in the main function. Because the array length is unknown and will be known after calling the function func(). yes, class definition is a mistake. It should be structure. I have corrected it.

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,082
    Quote Originally Posted by Shafiul
    However, for some reason, I can not declare the array or allocate a pointer with a specific size in the main function. Because the array length is unknown and will be known after calling the function func().
    Then you're just over-complicating this whole thing. No, you don't declare the array in main because there is no array in main, only a pointer. The function that main calls handles everything, and main just gets what it needs. For example:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int *create_numbers(size_t *size)
    {
        int *result = malloc(sizeof(result[0]) * 3);
        if (!result)
        {
            return NULL;
        }
    
        result[0] = 3;
        result[1] = 7;
        result[2] = 6;
    
        *size = 3;
        return result;
    }
    
    int main(void)
    {
        size_t size = 0;
        int *numbers = create_numbers(&size);
        if (numbers)
        {
            for (size_t i = 0; i < size; ++i)
            {
                printf("%d\n", numbers[i]);
            }
            free(numbers);
        }
        return 0;
    }
    Quote Originally Posted by Shafiul
    yes, class definition is a mistake. It should be structure. I have corrected it.
    But you're still using C++ syntax:
    • The label named public is invalid syntax since you cannot have a label outside of a function.
    • It looks like you're trying to declare a function as a member of the struct. You can declare a function pointer as a member of a struct, but not a function itself.
    • It is unnecessary to cast the return value of malloc.
    • nullptr was not declared.

    You should compile C code as C, not as C++, unless you are good enough at both languages to know what you're doing. You're not.
    Last edited by laserlight; 10-17-2020 at 02:53 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

  6. #6
    Registered User
    Join Date
    Oct 2019
    Posts
    34
    Super useful. Thanks Amanda.

  7. #7
    Registered User
    Join Date
    Oct 2019
    Posts
    34
    Meanwhile I am also sorry for my poor coding style. I will try to improve in near future.

  8. #8
    Registered User
    Join Date
    Oct 2019
    Posts
    34
    Thanks once again for your help. I am just afraid to ask, does free(numbers) actually free the first element of result array or all the elements?

  9. #9
    Registered User
    Join Date
    Jul 2009
    Posts
    6
    7.22.3.3 The free function

    "The free function causes the space pointed to by ptr to be deallocated ..."

    The entire allocated space based on a prior call to malloc / realloc / calloc and which has not yet been freed.

  10. #10
    Registered User
    Join Date
    Oct 2019
    Posts
    34
    Is there any way to free up the entire allocated space which was allocated inside a function of create_numbers?

  11. #11
    Registered User
    Join Date
    Sep 2020
    Posts
    126
    That last qn makes little sense. It works a bit like this:

    Your Code: Hey malloc(), I need 30 bytes to store some stuff in.

    malloc(): Sure, you can use the 30 bytes starting at memory address 1234560, I don't care about what you put in those 30 bytes, but be sure to let me know when they are no longer needed. And don't use more than 30 bytes, because I will give memory at 1234590 to others.
    ...
    Your code uses that memory for a while.
    ....
    Your code: Hey free()! I've finished with that memory malloc() gave me at 1234560.
    free(): Right you are, thanks for letting me know, I've let malloc() know that it can now issue it to others it as needed.

  12. #12
    Registered User
    Join Date
    Jul 2009
    Posts
    6
    Sure. That's done by tracking your own allocations and then freeing each when you wish.

    There are all sorts of ways to do this. Most people just use the manual approach. Save pointers in a list. Free the pointers in your list.

    There are advanced methods that have been around for many years, including a package originally called: The Boehm Garbage Collector

    See: A garbage collector for C and C++

  13. #13
    Registered User
    Join Date
    Oct 2019
    Posts
    34
    Thanks Hamster_nz. Thanks Jona.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A weird question.
    By IanKoro in forum C Programming
    Replies: 19
    Last Post: 06-08-2009, 12:00 PM
  2. Maybe a weird question
    By MarkookraM in forum C++ Programming
    Replies: 16
    Last Post: 08-25-2006, 12:11 PM
  3. weird question
    By heat511 in forum C++ Programming
    Replies: 2
    Last Post: 12-15-2003, 02:11 PM
  4. weird question
    By SavesTheDay in forum C Programming
    Replies: 3
    Last Post: 04-24-2002, 09:08 AM
  5. Weird Question maybe
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 12-27-2001, 07:30 PM

Tags for this Thread