Like Tree5Likes

[General Help] Dynamic Arrays and General Pointer syntax

This is a discussion on [General Help] Dynamic Arrays and General Pointer syntax within the C Programming forums, part of the General Programming Boards category; Hello, before I go further I would like to state that this is not for a homework assignment, but I ...

  1. #1
    Registered User
    Join Date
    Jul 2011
    Posts
    26

    [General Help][SOLVED] Dynamic Arrays and General Pointer syntax

    Hello, before I go further I would like to state that this is not for a homework assignment, but I would still prefer if I wasn't given the answer right off the bat. My goal is to write a very simply program that asks for a user input for the size of an array, adjusts the size, asks the user to input values and then prints out those values. I would prefer to split some of this up into functions, leaving as little in main as possible (I've been told that it's more efficient to do this).

    My Code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define CRT_NO_DEPRECATE
    
    void hurrdurr (double * array[], int size);
    
    int main (void)
    {
    	int *array, size;
    
    	printf("Enter the size of the array\n");
    	scanf("%i", &size);
    
    	array = (int*) malloc( size*sizeof(int));
    	printf("Enter some numbers");
    
    	hurrdurr (&array, size);
    
    	return 0;
    
    }
    void hurrdurr (int *array[], int size)
    {
    	int i;
    	for (i = 0; i < size; i++)
    	{
    		scanf("%lf", &array[i]);
    	}
    }
    I'm totally aware that my syntax isn't correct, but I also have very limited C experience. In fact, if my entire way of going about doing this isn't very good, by all means let me know.

    Thanks for any answers in advance, and I'll be as prompt as possible with replies.
    Last edited by Amberlampz; 07-26-2011 at 02:22 AM.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    void hurrdurr (double * array[], int size);
    ...
    void hurrdurr (int *array[], int size)
    Make sure those match, and get rid of those.

    Then call it like this:
    Code:
    int *myarray;
    ... malloc ...
    hurrdurr( myarray, size );

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Jul 2011
    Posts
    26
    Thanks for the quick response.

    Okay, so making those changes and adding the printf in the function makes it look like this:

    Code:
    void hurrdurr (int array[], int size)
    {
    	int i, j;
    	for (i = 0; i < size; i++)
    	{
    		scanf("%lf", &array[i]);
    	}
    	printf("The vales are:\n");
    	for (j = 0; j < size; j++)
    	{
    		printf("%i\n", array[j]);
    	}
    }
    But on the console it gives me 0's rather than the values I entered.

  4. #4
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,673
    Code:
    	for (i = 0; i < size; i++)
    	{
    		scanf("%lf", &array[i]);
    	}
    	printf("The vales are:\n");
    	for (j = 0; j < size; j++)
    	{
    		printf("%i\n", array[j]);
    	}
    Why are these different?

  5. #5
    Registered User
    Join Date
    Jul 2011
    Posts
    26
    Quote Originally Posted by whiteflags View Post
    Why are these different?
    Hey, look at that; I'm retarded.

    Program works. Thanks for the help!

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Amberlampz View Post
    I would prefer to split some of this up into functions, leaving as little in main as possible (I've been told that it's more efficient to do this).
    Breaking up a program into functions does not improve efficiency. The idea behind making functions is that they either get called from more than one place in the program, somehow modularize data, use variables not needed elsewhere in the code etc. Simply taking stuff out of main() for the sake of taking it out of main() does nothing... main is a function.

  7. #7
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,505
    It is more "efficient" to write the code, since you can focus on making each function do one thing well.

    As opposed to having everything in some vast sprawling main.

    50 lines is OK in a single function, 100 lines is pushing it, and 1000 lines in a function - well, someone is calling the psychiatrists.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  8. #8
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Salem View Post
    It is more "efficient" to write the code, since you can focus on making each function do one thing well.

    As opposed to having everything in some vast sprawling main.

    50 lines is OK in a single function, 100 lines is pushing it, and 1000 lines in a function - well, someone is calling the psychiatrists.
    I agree... but I've also written functions that are hundreds (but not yet thousands) of lines long because there was no natural breakpoint at which to separate things out. A prime example as a MIDI (music) file import function that ended up being close to 400 lines, most of it in a single do/while loop. There just wasn't any way to break it up without creating dozens of functions and suffering the "calling convention" overhead to do it.

    In hindsight I wish I had benchmarked that function, it was a very complex loop and it would have been interresting to see how much performance suffered if I did break it up.

    Maybe I'm a little different sort of programmer than most here (like that isn't already obvious???) but I don't see any problem with a straight through program tens of thousands of lines long. Functions are matters of reducing code size by replacing redundent code, compartmentalizing code, performing specific data manipulations, etc. Of course I use functions all the time but not simply because my main() is getting a little long.

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    6,266
    Quote Originally Posted by CommonTater View Post
    There just wasn't any way to break it up without creating dozens of functions and suffering the "calling convention" overhead to do it.
    Depending on how it's done, breaking a 400 line block into a number of smaller functions can help make the code easier to understand, hence to develop and maintain: small functions are generally easier to get right than larger functions. Code that calls a number of smaller functions (whether within a loop or not) can often be easier to understand if those functions are sensibly named.

    Of course, there are no absolutes. Any feature of a programming language can be abused, and functions are no different. Breaking up a large body of code into smaller pieces can make things harder to get right, if care is not taken in picking the pieces and naming them.

    "Calling convention" overhead is not always significant either - particularly if functions are inlined. It is premature optimisation to avoid breaking up a large body of code into smaller functions just to avoid function call overhead. It is better to focus initially on making the code understandable and ensuring it provides the intended results. Once that is done, use a profiler and other tools to identify performance hotspots and address them. The reason I describe avoidance of function call overhead as premature optimisation is that programmers are not particularly good at optimising code performance simply by inspection of code - and it is fairly rare, except in very tight loops, that function call overhead is a significant determinant of software performance.

    Quote Originally Posted by CommonTater View Post
    In hindsight I wish I had benchmarked that function, it was a very complex loop and it would have been interresting to see how much performance suffered if I did break it up.
    I agree. While it is certainly possible that breaking up code can compromise its performance, programmers can rarely estimate the impact reliably (say, within an order of magnitude) without measurements (benchmarking, profiling, etc).

    Quote Originally Posted by CommonTater View Post
    Maybe I'm a little different sort of programmer than most here (like that isn't already obvious???) but I don't see any problem with a straight through program tens of thousands of lines long. Functions are matters of reducing code size by replacing redundent code, compartmentalizing code, performing specific data manipulations, etc. Of course I use functions all the time but not simply because my main() is getting a little long.
    Personally, I don't worry about function sizes all that much either.

    My practical focus is on ensuring the code is understandable and correct. More often than not, that results in a set of small functions. However, I would prefer a large function that is understandable and correct over an equivalent one-liner that is a .......... to understand.
    Right 98% of the time, and don't care about the other 3%.

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by grumpy View Post
    Depending on how it's done, breaking a 400 line block into a number of smaller functions can help make the code easier to understand, hence to develop and maintain: small functions are generally easier to get right than larger functions. Code that calls a number of smaller functions (whether within a loop or not) can often be easier to understand if those functions are sensibly named.
    Hey, yer preaching to the choir here... I suppose my "average" function size (excluding windows message loops) is something like 10 to 20 lines. But, every so often I hit upon a monstrosity that just won't give me a break...


    My practical focus is on ensuring the code is understandable and correct. More often than not, that results in a set of small functions. However, I would prefer a large function that is understandable and correct over an equivalent one-liner that is a .......... to understand.
    Conditional agreement... This is one of the reasons I comment the daylights out of everything!

  11. #11
    Registered User
    Join Date
    Jun 2005
    Posts
    6,266
    Quote Originally Posted by CommonTater View Post
    Conditional agreement... This is one of the reasons I comment the daylights out of everything!
    On this, you and I differ. I include minimal comments in my code (I write more comments in untested sample code in forums than I ever do in practice).

    I prefer to structure the code itself so it is self-documenting (sensible variable names, sensible function names, structure, etc etc). My goal is to make the code self-documenting enough that I don't need comments. If my code is sloppy enough that it needs significant commentary, then I view that as a danger sign. It makes maintenance harder: there is nothing that ensures comments are updated if code is updated and comments out of sync with the code are very dangerous during code maintenance, as they encourage misunderstanding of the code.

    That's not saying I never use comments, but I do consider most people rely on them too much to cope with poor organisation of their code.
    stahta01 likes this.
    Right 98% of the time, and don't care about the other 3%.

  12. #12
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by grumpy View Post
    On this, you and I differ. I include minimal comments in my code (I write more comments in untested sample code in forums than I ever do in practice).
    ...
    That's not saying I never use comments, but I do consider most people rely on them too much to cope with poor organisation of their code.
    I always think "What if I have to come back to this in 5 years? Will I still be able to follow it?"

    For example:
    Code:
    // shuffle playlist
    void ShuffleList(void)
      { PWCHAR temp;  // swap pointer
        INT y;         // swap target
        srand(time(NULL));
        for (int x = LastLine; x > 0 ; x--)
          { y = rand() % x;   
            temp = Lines[x];  
            Lines[x] = Lines[y];
            Lines[y] = temp; } }
    In functions I tend to use "pigeon english" variable names and identify them in comments (old habits die hard). But for the most part I try, as you to make the code self-explanatory. For example variable swaps are so common as to be easily recognizable, so I don't worry too much about comments... But something like this...
    Code:
        try                                   
         { DWORD bom = *(DWORD*)rf;
           if ((bom == 0x0000FEFF) || (bom == 0xFFFE0000))  // utf32le bom  
             Exception(0xE0640002);                         // utf32be bom  
           else if ((bom & 0xFFFF) == 0xFFFE)               // utf16be bom
             { FlipEndian(rf,br);
               CopyWChar((PWCHAR) rf + 1); }
           else if ((bom & 0xFFFF) == 0xFEFF)               // utf16le bom
             CopyWChar((PWCHAR) rf + 1);  
           else if ((bom & 0xFFFFFF) == 0xBFBBEF)           // utf8 bom
             CopyMByte(rf + 3, br - 3);
           else                                             // no known bom, probe the file
             { if (! memchr(rf, 0x00, br))                  // 8 bit text has no nulls
                 CopyMByte(rf,br);                          // ansi / utf8 no bom
               else 
                { PBYTE lf = memchr(rf,0x0A,br);            // lf is always present as 1 byte.
                  if (!lf) 
                    Exception(0xE0640003);
                  if ((!(*(DWORD*)(lf - 3) & 0x00FFFFFF)) ||    //utf32be no bom
                       (!(*(DWORD*)lf & 0xFFFFFF00)))           //utf32le no bom
                     Exception(0xE0640002);    
                  if ((lf - rf) & 1)                        // big endian? (lf at odd offset)
                    FlipEndian(rf,br);                      // utf16be no bom  
                  CopyWChar((PWCHAR) rf);  } } }            // utf16le no bom
    ... I would never be able to follow after even a month without the comments.

  13. #13
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,673
    If I have to explain my own conditional tests I think I'm doing something wrong. If you'd let me I'd make macro functions to do that, or something.

  14. #14
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by whiteflags View Post
    If I have to explain my own conditional tests I think I'm doing something wrong. If you'd let me I'd make macro functions to do that, or something.
    Oh I can see what the conditionals are doing well enough... the comments remind me of why I'm using them... Especially in a case like that were the thing is up to it's buttox in magic numbers...

    Hey... it does happen!

  15. #15
    Registered User
    Join Date
    Jun 2005
    Posts
    6,266
    The difference is that I would structure the code to eliminate the comments where possible. It takes a bit more effort than writing comments, but the effort is worth it more often than not.

    For example, giving each of the hex constants suitably descriptive names and encapsulating tests in small (appropriately named) inline functions. The comments you have, for example, might provide a basis for selecting suitable constant or function names. I find that doing that often highlights chances for reuse (the same logic reused), or isolates any little bugs like an extra F in a hex constant - comments do not help with such things.

    It's a bit hard to be specific with a small snippet of code like that (a lot of the logic of creating self-documenting code is easier if you know the purpose of the code from a perspective of a caller, for example). If forced to choose though, I'd prefer commented code over an unintelligible mess, certainly.
    Right 98% of the time, and don't care about the other 3%.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner question about understanding general Syntax
    By lucidrave in forum C++ Programming
    Replies: 15
    Last Post: 08-13-2009, 03:57 PM
  2. arrays vs lists? And containers in general!
    By clegs in forum C++ Programming
    Replies: 22
    Last Post: 12-03-2007, 01:02 PM
  3. Pointer Passing Problems/ General Confusion
    By Swordsman in forum C Programming
    Replies: 11
    Last Post: 05-06-2007, 08:56 AM
  4. C in general
    By majoub in forum C Programming
    Replies: 3
    Last Post: 02-17-2005, 01:06 PM
  5. general pointer & malloc question
    By jstn in forum C Programming
    Replies: 2
    Last Post: 05-14-2002, 09:51 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21