Testing for TRUE and FALSE; A Problem Scenario

I wish they did better fact checking in these textbooks. Here’s a case in the C Programming book I’m reading. I was having problems with the following code:

FILE* spIn;
spIn = fopen("program73.dat", "r");
if(spIn != NULL)
 {
 printf("Could not open file.\a\n");
 exit(101);
 } // if open fails

Here’s the problem. The line if(spIn != NULL) always exits the program. However, if(!spIn) and if(spIn == NULL) both work fine.

The problem is that he was telling the program to terminate if the file opened successfully, the opposite of what he meant. The file pointer returns NULL if it’s not able to open the file. He told the program to exit if the pointer did not return NULL; in other words, the program terminated every time the file opened successfully. The other two checks I used checked to see if NULL was returned and the program would exit only if the file did not open successfully.

In a textbook, I certainly think the author should compile and test his programs to see if they work correctly a greater extent than this. However, this underscores a common problem for programmers. It’s very easy to get your tests backwards when testing for true and false conditions.

The best rule? Keep it simple and readable. If you have to take time to think through the logic, look for an easier way to write the condition. The second best rule, I guess, is to actually compile and run a program before you include it in a book, just to make sure it works correctly.

Aside | Posted on by | Leave a comment

Dynamically Allocating Memory for an Array

InPursuitYes, I know I haven’t written in a while. I’ve been busy. I decided to go back to college to learn the things I wanted to learn. I would get so far with C, then my eyes would glaze over. So, I’ve been taking 14 hours while working full time, to force myself to learn to code the things my mind typically avoids.

I’m finding that the course material is better for me than the tutorials I find online. One case in point is using malloc to dynamically allocate memory for arrays. This is something I wouldn’t have been able to do before. I’ve been taking C++ at school and it’s making C easier for me to understand. I’m taking the second semester of C++ in the spring, and a C class as well.

Enough of that, let’s create a dynamic array! I’ve taken someone else’s code, that I felt was incomplete, and rewritten it. This program runs fine on Linux. You may want to add #include <conio.h> to the include statements at the beginning if you are using a Microsoft OS.

// first we include the libraries
#include <stdio.h>
#include <stdlib.h>

// everything else, we'll do in main
int main() {
  // declare variables, including
  // array declared as int* array; a pointer
  // initially point it to NULL to avoid potential problems
  // programmers differ on whether the pointer should be type cast
  // a void pointer will return an error if you forget to include
  // the library but type casting makes the code compilable in C++
  int* array = NULL;

  // n will be a user-supplied number
  // i will be used as a counter in the for loop(s)
  int n, i;

  // Ask the user how many elements they want in the array
  printf("Enter the number of elements you want in the array: ");
  scanf("%d", &n);

  // this statement allocates memory for
  // n elements the size of an int
  array = (int*) malloc(n*sizeof(int));

  // check to see if the memory allocation failed
  // if it did, notify the user of the problem
  // and terminate the program with an error
  if(NULL == array)
  {
    puts("\nError allocating memory for array! Terminating!\n");
    return 1;
  }

  // everything's okay, so we'll ask the user to
  // enter a number for each element of the array
  for (i=0; i<n; i++) {
  printf("Enter number %d: ", i);
  scanf("%d", &array[i]);
  }

  // output the array one element at a time
  // then output its size for the user
  printf("\nThe Dynamic Array is: \n");
  for (i=0; i<n; i++) {
  printf("The value of %d is %d\n", i, array[i]);
  }
  printf("Size= %d\n", i);

  // when finished, free the memory that was allocated for the array
  free(array);

  // point the pointer to null
  // so you do not accidentally 
  // try to use it again with
  // unexpected results
  array = NULL;

  // return zero, exiting without errors
  return 0;
}

I thought it pretty strange that one example I saw didn’t show the user how to free the memory after the operation. Also, several didn’t bother setting the array pointer to point at NULL.

Memory is routinely freed once it is no longer in use by the program. If you want your program to run efficiently and cleanly, manually freeing memory that is no longer in use is more than just a good idea. The ability to directly manage memory like this is one of the big reasons to use a lower-level language like C or a mid-level language like C++. Assigning the pointer to NULL after freeing memory assures that you will get an error message if you accidentally try to use the pointer again to access the memory that has been freed.

Speaking of C++, I found the following example of doing the same thing in that language.

// i am not providing the full code here, just snippets

// start by declaring the pointer and initializing it to NULL
// C++ is a strongly typed language, so you must declare the 
// proper type for the array you want to use
int* a = NULL;
  
int n;           // declare the size variable

cin >> n;        // get the size from the user
a = new int[n];  // allocate memory for that number of ints
                 // note the comparative simplicity of the
                 // statement compared to the C statement
// increment through the elements
// put one more than the number of 
// that element in the element 
// will read 1 2 3 ... n when outputting 
for (int i=0; i<n; i++)
{
    a[i] = i+1;
}

// now iterate again, printing each array element
for(int i=0; i<n; i++
{
    cout << a[i] << endl;
}

// finished with the array, now free the memory
delete [] a;

// memory is free, now point the pointer a to NULL
// to prevent accessing the freed memory
a = NULL;

Memory that your program didn’t free will be freed when the program terminates but it’s best to free it manually where appropriate. Never free memory that wasn’t dynamically allocated – the results are unpredictable.

You must specify “[]” when deleting an array, but not for a single value. It isn’t possible
to delete only part of an array. As I mentioned before, setting the pointer to NULL isn’t strictly necessary, but it’s the best practice so that any further use of the pointer will produce an error. Some compilers will take care of that for you when you delete the
pointer but it’s best to do it anyway, just in case.

Posted in Computer/Web/Programming | Tagged , , , | 2 Comments

What Should be the Focus of Small Churches?

Church

I’m writing this article in reference to the article, http://careynieuwhof.com/2013/09/8-reasons-most-churches-never-break-the-200-attendance-mark/ that is circulating with some of my Christian friends. I hope you will read the original article and my thoughts on the subject.

Churches as Businesses? The question first on my mind is what emphasis should be placed on the structure of a church organization. I will be looking at the church as a business structure, which is basically what that article is about, and discussing the goals that Christianity dictates to our organizations. Let’s start with this quote from the article.

“You know why most churches still don’t push past the 200 mark in attendance You ready? They organize, behave, lead and manage like a small organization.

I am a business person and I can tell you one thing about business. The structure of your organization is not what brings business through the doors. The organizational structure is there to efficiently handle the current business load and, hopefully, increases in business. Structure in and of itself does not provide growth for an organization. The marketing and advertising that is incorporated into the structure of the business is what promotes growth.

“The pastor is the primary caregiver. … When the pastor has to visit every sick person, do every wedding, funeral and make regular house calls, he or she becomes incapable of doing other things. That model just doesn’t scale. If you’re good at it, you’ll grow the church to 200 people and then disappoint people when you can’t get to every event any more.”

Again the article is not talking about the organization structure providing growth. It talks about distribution of work in an organization that is not able to meet the growth and needs that it already has. In a small church, where the pastor can easily handle these things, reorganization makes no sense. Organizing like a big organization can actually do more harm than good.

I’ll give you an example. I know of a church that regularly has less than 200 in attendance. They try to organize like a bigger church in several ways. One notable way is a program of volunteers that makes calls to people who have missed church for several weeks. In such a small church, many of the people know each other but this is not necessarily the case. Instead of just asking someone who knows the person to call and see if there’s a problem, the church hides behind the anonymous mask of callers, without regard to the relationships of the people involved. I know for a fact that several members who left the church saw it as an inexcusable insult that they were put on a call list and contacted by people they didn’t even know, even though friends of theirs were part of the program. In a church that small, organizing like a big church in this way was actually detrimental.

Doing something unnecessary that places a dividing line between the clergy (or any aspect of the church’s administration) and the lay people in the church is not a benefit and very often these things cause harm to the church.

“The leaders lacks a strategy. Many churches today are clear on mission and vision. What most lack is a widely shared and agreed-upon strategy. You vision and mission answers the why and what of your organization. Your strategy answers how. And how is critical.”

From an organization standpoint, I agree with this. As a Christian, I believe the mission dictates the vision and the strategy. Jesus told us the one mission all Christians have when he said, “Love the Lord your God with all your heart, mind, soul and stregnth, and love your neighbor as yourself.” How do we know that this is our highest calling? Because he added, “On this all the law and the prophets hang.”

In other words, love of God and our fellows should dictate everything we do and everything we believe. Our doctrine, our strategy, should be about finding and meeting real needs in the lives of other people, showing them God’s love in our lives. Our goal is not to bring people into the doors of the church. Our goal is to love in a way that will transform the lives of the people around us. We meet needs as we find them. If people aren’t in your church because they are seeing this love and seeking it in their own lives, all your strategies and creativity are meaningless. Love and need dictates your strategy.

“True leaders aren’t leading. In every church, there are people who hold the position of leadership and then there are people who are truly leaders (who may not hold any position in your church). Release people who hold titles but aren’t advancing the mission and hand the job over to real leaders.”

Absolutely! Elders in the church should be people who are, well, our elders. They should be rich in life experience and wisdom as Christians who follow the law of love. In other words, they should not be young in years, in thinking, or young as Christians. They should have a track record of selflessness in their community. A true elder is a loving servant who demonstrates this in daily life. In fact, every person in the church should be trained to be a servant. The separation between the paid church members (leaders and administrators) and the lay membership should be blurred as the church follows one goal, the realization of the law of love in every individual who walks through the doors of the church.

“Too many events and programs that lead nowhere. Activity does not equal accomplishment.”

Did you notice that I skipped a few lines from his article? Let’s just handle those with this small thought. Need dictates how we organize. This means that you organize for the amount of “business” coming through your organization. However, love dictates our mission and our actions. It supercedes every other doctrine or creed.

Your activities and programs should not be geared toward bringing more people into the church. Your activities and programs should be planned because there is a need in the community, in the lives of individuals, that you can meet. Every activity should be a celebration of love, toward God and toward people. If you do this, people will be drawn to the love coming from the people in your church.

“I realize the diagnosis can sound a little harsh, but we have a pretty deep problem on our hands. And radical problems demand radical solutions.”

I absolutely agree with this! However, I think our deep problem involves authors like this who think of the Church as a business or a non-profit organization. If your church cannot exist without the organizational and legal structure, it is a club, not Church.

Your church should be part of the one, true Church, following the law of love in all things. How you organize should always be dictated by need. What you do should be dictated by love. Seeking to be more like mega-churches is seeking to walk away from a relationship with God and the true Church. The supreme law is about relationships and we cannot have real relationships with people as long as our focus is on numbers, whether those numbers be the members of our churches or the dollars we need to pay the bills.

If your church crawls to 10 members and the property is foreclosed because you can’t pay the mortgage, will you consider the church a failure and disband? If you do, you have let the world win. None of these things matter! Meet as Christians because you love God and others, because you want to have a relationship with God and others. On this, the continuation of the one, true Church of the living God depends.

In my opinion, churches should not have mortgages. When you owe someone money, you are their servant, and your church should serve only one master. If the church is worried about bringing in money to pay the bills, it has already lost Christ as its focus.

In my opinion, churches should not depend on being non-profit organizations. This places the church under the authority of the government, allowing it to dictate how the church will operate and organize. When you are under the authority of the government, your church is, again, trying to serve more than one master.

The Church is love for God and love for people. The law of love will direct and guide it. A church that seeks to be popular, building a cult of personality for its pastor or putting on a big media show, has already lost and is no longer the bride of Christ, the Church of the living God.

Posted in Business/Politics, Philosophy/Religion | Leave a comment

Old Dog New Tricks

I taught my dog a new trick today. We we’d playing ball in the pool and she bounced it out with her nose. I told her to get out. She did. I told her to get the ball. She got it and began walking toward the house, sadly assuming swim time was over. I coaxed her back and into the pool. We repeated this one other time she bounced it out with her nose and it was too far to reach. I have the best dog in the world!

#stuffyouteachyourdogtodobecauseyouaretoolazy

Posted in Lifestyle/Family/Friends | Leave a comment

My Secret to Success

I have a secret. This secret drives everything I do and it is what led me from working an 8 to 5 job to owning a media company. I’m going to share that secret with you right now.

I don’t ask anyone’s permission.
Continue reading

Posted in Business/Politics, Computer/Web/Programming, Entertainment/Media, Philosophy/Religion | Leave a comment

C Programming – Pointer to argc

InPursuitJust for fun, here’s a little program that uses a pointer to return the number of arguments that are submitted to the program at the command line.

#include <stdio.h>

int main(int argc, char argv[])
{
int *ptrArgc;

ptrArgc = &argc;
printf("\n\nOutput number of arguments in argc: %d \n\n", *ptrArgc);

printf("\n\nOutput memory address of argc: %d \n\n", ptrArgc);

return 0;

}

First, notice the line that declares the main() function in the program. The “int argc” declares an integer that automatically fills itself with the number of arguments entered at the command line when you run the program. The name of the program is the first argument, so the smallest number it can return is 1. The “char argv[]” is a character array that contains all the arguments entered at the command line, with “argv[0]” returning the name of the program itself.

The line “int *ptrArgc;” line declares a pointer and the “ptrArgc = &argc;” line assigns the memory address of argc to the pointer.

When printf() is used for the first time, ptrArgc is dereferenced with an asterisk. This causes it to print the value contained in argc instead of the memory address.

The second time printf() is used, ptrArgc is not dereferenced, so it prints the number actually contained in ptrArgc, which is the memory address that holds the value for argc.

Try compiling and running this program, entering different numbers of arguments at the command line. Notice the assigned memory address changes when you run the program.

Posted in Computer/Web/Programming | Tagged , , , , , , , , , | Leave a comment

C Programming – Binary to Decimal Converter

InPursuit

There are 10 kinds of people in this world, those who understand binary and those who don’t. — Unknown

While reading a book on assembly language programming, I came across a section that discussed different numbering systems used and how to convert from one to another. I gave myself some assignments to complete one at a time. Here’s the first one. This converter takes an 8-bit, unsigned binary number, entered at the command line as argv[1], and converts it to its decimal equivalent.

This was a fun assignment. It can easily be modified to take a 16-bit number instead, simply by changing the number of iterations in the for() loop and the starting number for the myCount variable. It uses the pow() function in math.h but everything else in the code is pretty straight forward. I have not tested it fully but it does compile and work using the Visual Studio 2012 command line compiler.

// function receives a string containing an 8-bit, unsigned binary integer 
// returns the decimal integer value of the binary integer
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(int argc, char *argv[])
{
 const char *binNumber = argv[1];
 int decNumber = 0;
 int myDecCount;
 int myCount = 7;

 puts("\n\nBinary to Decimal Converter\nby David Peterson Harvey\n\n");

if (argc == 2)
 {
 printf("%s converts to %d\n\n", binNumber, decNumber);
 // if argv[1] == 8 digits long, binNumber = {argv[1]};
 if(strlen(argv[1]) == 8)
 {
 for(myDecCount=0; myDecCount <=7; myDecCount++) 
 {
 if(binNumber[myCount] == '1')
 {
 decNumber = decNumber + pow(2, myDecCount);
 }
 printf("\nCurrent number %d.\nCurrent count %d.\n\n", myDecCount, decNumber);
 myCount--;
 }
 }
 else
 {
 printf("You must enter a binary number 8 digits long. You entered %s.\n\n", argv[1]);
 }
 }
 else
 {
 printf("To use program:\n\n\t %s 8-digit_binary_number\n\n", argv[0]);
 }
return 0;
}
Posted in Computer/Web/Programming | Tagged , , , , , , | Leave a comment