#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    26
    Rep Power
    0

    C Programming mental block


    I ‘m attempting to learn C programming, and have a mental block with the following textbook problem, and hope that someone can provide a pseudocode example so that I can understand the approach to this problem.
    The problem to solve is:
    Write a program that initializes a two-dimensional array-of-double and uses one of the copy functions from exercise 2 to copy it to a second two-dimensional array. (Because a two-dimensional array is an array of arrays, a one-dimensional copy function can be used with each subarray.)
    My solution for “exercise 2” is as follows:


    Code:
    #include <stdio.h>
    #define SIZE 5
    void copy_arr(double source[],double target1[],int);	// fn array prototype
    void copy_ptr(double *ptr1,double *ptr2,int);	//fn ptr prototype
    int main(void)
    
    {
    int i;
    double source[]={1.1,2.2,3.3,4.4,5.5};	//initialize array
    double target1[SIZE];				//declarations
    double target2[SIZE];
    double *ptr1, *ptr2;
    ptr1 = source,ptr2 = target2;			//initialize ptrs
        copy_arr(source,target1,SIZE);		//function calls
        copy_ptr(ptr1,ptr2,SIZE);
        return 0;
    }
    void copy_arr(double source[],double target1[],int n)	//copy by array format
    {
        for(int i=0;i<SIZE;i++)
        {
       	 target1[i] = source[i];         //initialize copy
        }
        for(int i=0;i<SIZE;i++)
        {
       	 printf("%4.1f",target1[i]);   //print copy
        }
        printf("\n");
    }
    void copy_ptr(double *ptr1,double *ptr2,int n)		//copy by pointer format
    {
        for(int i=0;i<SIZE;i++)
        {
        	*(ptr2+i) = *(ptr1+i);         //initialize copy
        }
        for(int i=0;i<SIZE;i++)
        {
       	 printf("%4.1f",*(ptr2+i));   //display copy
        }
        printf("\n");
    }
    Thanks for any help you can provide.
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,905
    Rep Power
    481

    Clean up exercise 2.


    • Your display operations are duplicate code. You had written the same print statements in both copy functions. "display" should be separate from "copy" except perhaps in debugging. I've extracted the display functionality into a new function and called the display in main following the copy operations.
    • In your copy functions you used an upper loop limit of SIZE instead of the function argument n. Complete and good testing is difficult! Your test will not show this problem.
    • I think I had a third item; it is forgotten. Any other code arrangements I made were for my own pleasure or to satisfy my lazy compilation command line.
      c.c:12:3: error: 'for' loop initial declarations are only allowed in C99 mode
      c.c:12:3: note: use option -std=c99 or -std=gnu99 to compile your code
      c.c: In function 'copy_ptr':
      c.c:16:3: error: 'for' loop initial declarations are only allowed in C99 mode
      c.c: In function 'main':
      c.c:21:7: warning: unused variable 'i' [-Wunused-variable]

    Code:
    #include <stdio.h>
    #define SIZE 5
    
    void display(double*a, int n) {
      int i;
      for (i = 0; i < n; ++i)
        printf("%4.1f",a[i]);
      putchar('\n');
    }
    
    void copy_arr(double source[],double target1[],int n) {
      int i;
      for(i=0;i<n;i++)
        target1[i] = source[i];
    }
    
    void copy_ptr(double *ptr1,double *ptr2,int n) {
      int i;
      for(i=0;i<n;i++)
        *(ptr2+i) = *(ptr1+i);
    }
    
    int main(void) {
      double
        source[]={1.1,2.2,3.3,4.4,5.5},
        target1[SIZE], target2[SIZE],
        *ptr1, *ptr2;
      ptr1 = source, ptr2 = target2;
      copy_arr(source,target1,SIZE);
      display(target1, SIZE);
      copy_ptr(ptr1,ptr2,SIZE);
      display(ptr2, SIZE);
      return 0;
    }
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    26
    Rep Power
    0
    Thanks for the professional clean-up, which is appreciated. But the important question regarded my mental block in the approach to the problem stated, which was an algorithm to modify the code for a 2-D array.

    I repeat:

    hope that someone can provide a pseudocode example so that I can understand the approach to this problem.
    The problem to solve is:

    Code:
    Write a program that initializes a two-dimensional array-of-double and uses one of the copy functions from exercise 2 to copy it to a second two-dimensional array. (Because a two-dimensional array is an array of arrays, a one-dimensional copy function can be used with each subarray.)
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,905
    Rep Power
    481
    I do not know how to show in pseudo code what the c syntax should look like. Sorry. Sorry also that you seem unconcerned with incorrect programs. "...thank you but..."...i need to advance to the next lesson so i can foul that up as well.
    Code:
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    /* exercise 3 */
    
    #include <stdio.h>
    
    #define DIM(A) (sizeof(A)/(sizeof(*(A))))
    
    void display(double*a, int n) {
      int i;
      for (i = 0; i < n; ++i)
        printf("%4.1f",a[i]);
      putchar('\n');
    }
    
    void copy_arr(double source[],double target1[],int n) {
      int i;
      for(i=0;i<n;i++)
        target1[i] = source[i];
    }
    
    void copy_ptr(double *ptr1,double *ptr2,int n) {
      int i;
      for(i=0;i<n;i++)
        *(ptr2+i) = *(ptr1+i);
    }
    
    double source[70][30]={{1,2,3},{4,5,6,999},{666}}; /* initializing a 2D array */
    
    int main(void) {
      double target[2][3];
      copy_arr(source[0], target[1], 3);		  /* reverse */
      copy_ptr(source[1], target[0], DIM(target[0])); /* rows */
      {
        int i;
        for (i = 0; i < DIM(target); ++i)
          display(target[i], DIM(*target));
      }
      return 0;
    }
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    26
    Rep Power
    0
    Sorry that you seem to think that I'm "unconcerned with incorrect programs". My code was correct for c99, but not nearly as elegant as your professional version, where you've separated the functions properly, which I, as a newbie, did not think of.
    My code may not qualify as 'portable, but Fedora won't even compile if 'warnings' occur, as my compiler is set.

    Comments on this post

    • b49P23TIvg disagrees : Your program is outright wrong. In your copy functions you used an upper loop limit of SIZE instead of the function argument n.
  10. #6
  11. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,184
    Rep Power
    2222
    I have to say that I'm appalled by your attitude about C99, which is not well supported. Who actually uses C99, anyway? Sure, the academics are pushing it, but I know of no professional who uses it or would be inclined to. It reminds me of Apple computers and the way that they pushed their computers into the schools thinking that those kids would then graduate and buy computers for the workplace. No, what happened was that those kids would graduate and have to learn to use an entirely different computer, the ones that their bosses would buy. Outside of graphic arts and publishing, how many businesses use Apple instead of Windows or Linux?

    That's not what I have a problem with, but rather your attitude that you are entitled to make it unnecessarily difficult for us to provide you with the free (for you, but which costs us our valuable time) help that you feel entitled to. Rather, your attitude should be to make it as easy for us to help you as you can make it. Do you really need to declare those variables on-the-fly? What advantage does that buy you that would compensate for the disadvantage of us not bothering to help you because we have to modify your code in order to get it to compile? Is it really worth it to you to discourage so many of us here from helping you? Think about that.

    Write a program that initializes a two-dimensional array-of-double and uses one of the copy functions from exercise 2 to copy it to a second two-dimensional array. (Because a two-dimensional array is an array of arrays, a one-dimensional copy function can be used with each subarray.)
    The answer to your problem is right there. In the main function, use a for loop to iterate through all the rows, passing each row to the copy function. Much as b49P23TIvg did in Message #4 (except I don't know why he reversed two rows and he didn't use a loop since he only did it for two rows). But I guess you didn't bother to read that either.

    Comments on this post

    • b49P23TIvg agrees : Dave reversed some rows to playfully demonstrate the utility of the wonderful array copier.
  12. #7
  13. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,114
    Rep Power
    1803
    Originally Posted by dwise1_aol
    In the main function, use a for loop to iterate through all the rows, passing each row to the copy function.
    The "hint" is missing a trick it certainly need not that complicated. Two dimensional arrays are contiguous, so only a single copy is required.

    For example given:
    Code:
    double data[3][2] = { { 1.1, 1.2, 1.3 },
                          { 2.1, 2.2, 2.3 } } ;
    The arrangement in memory is:
    Code:
    { 1.1, 1.2, 1.3, 2.1, 2.2, 2.3 }
    which is identical to a 1 dimensional array of 6 (3 x 2) doubles.

    So given:

    Code:
    double target[3][2] ;
    The answer is simply:
    Code:
    copy_arr( data, target, sizeof(target) / sizeof(double) ) ;
    or less maintainably:
    Code:
    copy_arr( data, target, 6 ) ;
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    26
    Rep Power
    0
    Thanks for making me aware that there actually was code in the thread by B49P23TIvg in post 291008. On my screen, there appeared to be an empty "code" box, which I neglected to scroll down far enough to see that there was actually something there. Indeed, that alone gave a clear answer to my question. That oversight has led to a lot of the subsequent confusion here.

    Yes, I'm aware of the contiguity of array elements, and appreciate the further clarification in answer of my question.

    As dwise1_aol said:
    Much as b49P23TIvg did in Message #4 (except I don't know why he reversed two rows and he didn't use a loop since he only did it for two rows). But I guess you didn't bother to read that either.
    turned out he was correct: I didn't read it cause I didn't see anything there. But he 'reversed the rows' to further clarify the parsing applicable to each row.
    And I still don't understand dwise1's accusation that my code wasn't compiled. My Fedora setup is very picky, and compiled my original code without error.
    Considering that the history of any subject is important, I myself am disappointed that C programming could be held in such disdain. I'm vaguely familiar with object based programming (Access basic), but it's an intellectual pleasure to understand what it's based on.
    Again, thanks for all the help.
  16. #9
  17. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,184
    Rep Power
    2222
    Originally Posted by atlantis43
    And I still don't understand dwise1's accusation that my code wasn't compiled. My Fedora setup is very picky, and compiled my original code without error.
    Considering that the history of any subject is important, I myself am disappointed that C programming could be held in such disdain. I'm vaguely familiar with object based programming (Access basic), but it's an intellectual pleasure to understand what it's based on.
    Perhaps you should consider what I actually wrote:
    Originally Posted by dwise1
    I have to say that I'm appalled by your attitude about C99, which is not well supported. Who actually uses C99, anyway? Sure, the academics are pushing it, but I know of no professional who uses it or would be inclined to. It reminds me of Apple computers and the way that they pushed their computers into the schools thinking that those kids would then graduate and buy computers for the workplace. No, what happened was that those kids would graduate and have to learn to use an entirely different computer, the ones that their bosses would buy. Outside of graphic arts and publishing, how many businesses use Apple instead of Windows or Linux?

    That's not what I have a problem with, but rather your attitude that you are entitled to make it unnecessarily difficult for us to provide you with the free (for you, but which costs us our valuable time) help that you feel entitled to. Rather, your attitude should be to make it as easy for us to help you as you can make it. Do you really need to declare those variables on-the-fly? What advantage does that buy you that would compensate for the disadvantage of us not bothering to help you because we have to modify your code in order to get it to compile? Is it really worth it to you to discourage so many of us here from helping you? Think about that.
    Please point out the exact words where you allege that I had said that you had not compiled your code. I do not doubt that it compiled with your compiler which I do not doubt supports C99. The problem I was pointing out is that in the real world -- you know, the one where a lot of us work -- C99 is not very well supported. I know that many participants on this forum use compilers that do not support C99 and therefore they would not be able to compile your code. OTOH, everyone here can compile a C89 program. For that matter, all the professional C programmers I know work with C89, not C99. And only some current compilers bother to support C99.

    So why insist on using C99 features [i]which are not even necessary[i] and which accomplishes nothing more than to prevent many of us from being able to help you?

    Did you understand it this time?
  18. #10
  19. Commie Mutant Traitor
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2004
    Location
    Alpharetta, GA
    Posts
    1,806
    Rep Power
    1570
    Originally Posted by dwise1_aol
    The problem I was pointing out is that in the real world -- you know, the one where a lot of us work -- C99 is not very well supported. I know that many participants on this forum use compilers that do not support C99 and therefore they would not be able to compile your code. OTOH, everyone here can compile a C89 program. For that matter, all the professional C programmers I know work with C89, not C99. And only some current compilers bother to support C99.
    I am quite surprised and puzzled by this claim, as it is my experience that most C programmers have been using C99 for some time now, and many are rapidly switching to C11. While C programmers aren't as inclined to switch to newer standards as C++ programmers, they all seem grateful for the newest developments.

    The claim that lack of support is an issue also surprises me. Which modern compilers don't support C99? I cannot think of any that don't support it as an option, and most support it by default - including the current version of GCC (after 4.5), which let's face it, is the only really important one these days. The 'new' standard has been in production use for over ten years, and while there are few reasons to choose C99 features specifically, poor support for the standard doesn't seem like much of a reason not to do so.

    Admittedly, outside of the Linux operating system kernel and utilities - which don't follow the standards any which way, anyway - the majority of C coding today is in the embedded field, but even there, where many of the compilers are indeed quite dated, I would have expected that fourteen years would be enough time for the standard to get supported.

    As for it being an 'academic' choice to use C99, to the contrary, universities - especially outside of the US - rarely practice anything like modern standards. The nearly universal use of the ancient Turbo C compiler in India and many other countries for teaching, and the extreme resistance to change in general among college professors and curriculum standards developers, has meant that few programmers are taught the newer standards, but this does not mean they aren't used in the business world.
    Last edited by Schol-R-LEA; October 31st, 2013 at 01:02 AM.
    Rev First Speaker Schol-R-LEA;2 JAM LCF ELF KoR KCO BiWM TGIF
    #define KINSEY (rand() % 7) λ Scheme is the Red Pill
    Scheme in ShortUnderstanding the C/C++ Preprocessor
    Taming PythonA Highly Opinionated Review of Programming Languages for the Novice, v1.1

    FOR SALE: One ShapeSystem 2300 CMD, extensively modified for human use. Includes s/w for anthro, transgender, sex-appeal enhance, & Gillian Anderson and Jason D. Poit clone forms. Some wear. $4500 obo. tverres@et.ins.gov
  20. #11
  21. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,184
    Rep Power
    2222
    Originally Posted by Schol-R-LEA
    I am quite surprised and puzzled by this claim, as it is my experience that most C programmers have been using C99 for some time now, and many are rapidly switching to C11. While C programmers aren't as inclined to switch to newer standards as C++ programmers, they all seem grateful for the newest developments.
    I have raised this question several times on this forum and have received no response to it. I think that it is a valid question to ask how prevalent the use of C99 is among professionals, which is to ask how much does industry use C99 as opposed to C? (ANSI C (1989) being what is commonly meant by "C", with C99 having to be specifically referred to as "C99")

    However, upon further reflection this morning as I was writing this, I find that the question and the answer are not very clear at all. A professional programmer who programs solely in ANSI C (1989) could very well be using a C99 compiler and hence would technically be "programming in C99". Even if I were to change the question to mean those who deliberately make use of C99 features, that would also not provide a clear answer since part of what C99 did was to incorporate extensions to the language that had been implemented in several compilers (eg, snprintf), so even programmers programming in ANSI C and using an compiler that does not support C99 but using that compiler's extensions that got included in the C99 standard would still be "deliberately making use of C99 features."

    So as it turns out, this entire question becomes very murky very fast. I guess the best way I can ask this question would be something like: "How many professional programmers deliberately choose to use a compiler because it supports C99 and then design their programs to deliberately make use of C99 features that are not extensions to C compilers, such as C++'s intermingling of declarations and code, variable-length arrays, inline functions, not allowing variables or functions to be implicitly declared as int (just about the only C99 feature I think is a really good idea), or allowing identifiers to contain characters outside of the standard character set (¿eg, accented vowels?)."

    I believe that you do not really disagree with that question, since you wrote: "... while there are few reasons to choose C99 features specifically, ...". And even if they really need to use variable-length arrays, they can still do that with ANSI C. I just played around with a couple ideas, including a function I got from Wikipedia's article on variable-length arrays (http://en.wikipedia.org/wiki/Variable-length_array -- written in C99 so I had to fix it):
    Code:
    int main()
    {
        int x=42;
    
        printf("ANSI C version of variable-length arrays:\n");
        
        {
            int a[x];
            int i;
            
            for (i=0; i<x; i++)
                a[i] = i;
            
            for (i=0; i<x; i++)
                printf(" %d",a[i]);
            
            printf("\n");
        }
        
        return 0;
    }
    
    float read_and_process(int n)
    {
        float vals[n];
        int i;
     
        for (i = 0; i < n; i++)
            vals[i] = i;   // replaced a call to an undefined function
        return 42.0f;   // replaced a call to an undefined function
    }

    Originally Posted by Schol-R-LEA
    The claim that lack of support is an issue also surprises me. The claim that lack of support is an issue also surprises me. Which modern compilers don't support C99?
    Two very common examples are Microsoft Visual Studio as of 2012 and also MinGW gcc. And that does not include the compilers that don't support it fully.

    At http://en.wikipedia.org/wiki/C99#Implementations, Wikipedia lists 20 compilers and rates them by their support for C99. Out of those 20:
    • 5 offer "full" support, including the Sun and IBM compilers.
    • 6 support it "mostly", including gcc (gcc on Linux, at least, but not the MinGW gcc port).
    • 7 offer "partial" support, including Watcom C, whose support "are enabled only through an undocumented command-line switch.", so C99 support must not be that important to them.
    • 2 offer "no" support. That includes Microsoft Visual C++ as of 2012, though they report that VC++ 2013 is planned to include libraries that offer some support.

    But that begs the question of how many compilers are in use that do or don't support C99. To arrive at those figures, we'd need to find out what each compiler's market share is, information that I don't have. I think it's safe to assume that Microsoft's Visual Studio and its free Visual C++ Express are very well represented out in the wild, which would lower the overall support for C99 even more.

    So then, no, C99 does not enjoy anywhere close to universal support. Of the several compilers that I normally use (Visual Studio, past versions of Visual C++, MinGW gcc, compilers for embedded systems), none of them support C99. On my laptop I can run Ubantu under VMWare, but I haven't yet used its gcc for anything other than ANSI C and C++; in order to transfer a forum member's program into that environment would not be worth the trouble.

    And what is the level of full support for ANSI C (1989)? Outside of smaller implementations that leave out parts of the standard library that aren't needed (eg, stdio for embedded systems), I'd be very surprised if it didn't have universal support. So if you want your code to be universally portable, stick with ANSI C and avoid C99-specific features.

    Originally Posted by Schol-R-LEA
    ... and while there are few reasons to choose C99 features specifically, poor support for the standard doesn't seem like much of a reason not to do so.
    That is not at all the argument I am making. Rather, the argument I am making is based on the support this forum's members are able to provide for C99. That by unnecessarily using C99 features (namely the C++ ability to intermingle declarations and code), the seeker of help is automatically shutting out a large segment of this forum's population.

    I base this on observation, which should be supported, or not, by a poll of what compilers everybody here uses -- as I keep telling newbies about what their code is doing, "Knowing is better than guessing." Some do use gcc on Linux, but not everybody uses Linux or has access to a Linux system. I believe that more members use Windows than Linux, which could be put to a poll. What compilers do the Windows users use? I observe that many here use MinGW gcc, mostly via Dev-C++, Code::Blocks, or similar IDEs in which MinGW gcc comes bundled -- and I'm sure that they don't even realize they're using MinGW. Many use Visual Studio. Neither MinGW gcc nor Visual Studio supports C99. Hence, the only way that many here could get a C99-specific program to compile would be for them to have to fix the program first, which is not only extra work that should not be imposed on us, but also defeats the purpose.

    Hence my actual argument, which is not what you stated:
    Originally Posted by DWise1
    So why insist on using C99 features which are not even necessary and which accomplishes nothing more than to prevent many of us from being able to help you?



    Originally Posted by Schol-R-LEA
    As for it being an 'academic' choice to use C99, to the contrary, universities - especially outside of the US - rarely practice anything like modern standards. The nearly universal use of the ancient Turbo C compiler in India and many other countries for teaching, and the extreme resistance to change in general among college professors and curriculum standards developers, has meant that few programmers are taught the newer standards, but this does not mean they aren't used in the business world.
    Again, I based that on observation, in that I have yet to see any C99 questions arise in the industry, but rather only from students posting here. That gives me the impression that it's more an academic thing than a professional one.

    I think the nearly universal use of Turbo C overseas is because it was one of the first popular compilers to be available for free. Also, yes, I believe that teachers can be very resistent to change, because once they have done all that work creating the curriculum and lesson plans, they then live off of them for the rest of their professional lives. Plus there's the resistence to having to learn yet another compiler. However, as that deadwood ages out, their replacements, having to develop their own curricula, will be much more likely to bring it up-to-date.

    Plus, there's the effect of accidentally falling into C99 practices. From observation, most of the C99 posters have been students using gcc under Linux. It may very well be that they aren't being taught to use C99, but because gcc is automatically set up to support C99 (I assume) these students get into the lazy habit of intermingling declarations and code just because gcc allows them to get away with it. Or the teacher found that he could do that, so he passes it on to his students.
  22. #12
  23. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,114
    Rep Power
    1803
    Originally Posted by atlantis43
    Thanks for making me aware that there actually was code in the thread by B49P23TIvg in post 291008. On my screen, there appeared to be an empty "code" box, which I neglected to scroll down far enough to see that there was actually something there.
    Exercise caution when reading B49P23TIvg's posts. He likes to place traps, red-herrings and obfuscations, which I might charitably assume are placed to ensure that you are thinking rather than merely being a help vampire, but I would not discount the possibility that he is actually just evil :eek: .
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    26
    Rep Power
    0
    Sorry also that you seem unconcerned with incorrect programs. "...thank you but..."...i need to advance to the next lesson so i can foul that up as well.
    Well, at least I now have some idea what this comment early in this string meant.
    Exercise caution when reading B49P23TIvg's posts. He likes to place traps, red-herrings and obfuscations, which I might charitably assume are placed to ensure that you are thinking rather than merely being a help vampire, but I would not discount the possibility that he is actually just evil
    And after this comment, I realize why I thought that the "code" was intentionally left blank in that response.

    Obviously, much of the content of these last posts is way over my head, so atleast in respose to:
    Did you understand it this time?
    I can only say that I understand the complexity of it.

IMN logo majestic logo threadwatch logo seochat tools logo