C vs C++: Arrays

In this lecture, we will see how the C language handles arrays. And as before, you will see that many differences are superficial and what you've learned for C++ in this class nicely applies to C. As a reminder of the differences we've already covered:

Today we will look at arrays and strings. The short description is that C requires you to be more explicit with how much memory you need for an array, but after that, pointers and array usage is the same.

Allocating Memory for an Array: malloc or calloc

C++C
int* nums = new int[12];

#include <stdlib.h>
int* nums = malloc( 12*sizeof(int) );

In C, we instead use the keywords malloc or calloc. They're almost, but not exactly, the same.

malloc

The prototype for malloc is:
void* malloc(int);

calloc

C++C

double* A = new double[10];
for(int i=0; i<10; i++)
  A[i] = 0;

#include <stdlib.h>
double* A = calloc(10, sizeof(double));

The choice between malloc and calloc is largely a personal preference between the two, as long as you're knowledgeable about these differences.

Filling an Array with scanf

Remember that scanf requires a pointer to know which memory address will be filled. For example, reading an int:

int* nums = malloc( 10*sizeof(int) );
for( int i = 0; i < 10; i++ )
   scanf("%d", &nums[i]);   // we just need the & to get the address of the array cell

free

Remember to delete your memory allocation when you're finished with your arrays!

The C equivalent of delete is the function free:

 
free(intArr);
free(doubles);

Strings

Null character

As we learned from the previous lecture, strings in C are instead explicit arrays of chars. There is a small catch, though:

The final char of your array must be a null character (ASCII code 0).

So, if you were to encode the word "hi" as a C string, you would need an array of size three:


char str[3];
str[0] = 'h';
str[1] = 'i';
str[2] = 0; //alternatively, the character '\0'
print("%s\n", str);

Using c-style strings

#include <string.h>

This library provides a wide variety of useful string functions in string.h.

Copying: strcpy()

You can copy strings using the strcpy function. The prototype is as follows:
char* strcpy(char* s_to, const char* s_from);
This function copies string s_from to s_to. For conveniece, the function returns s_to as well.

Sample code:


#include <iostream>
using namespace std;

string s1;
s1 = "hello world";
cout << s1 << endl;

#include <string.h>


char s1[128];
strcpy(s1, "hello world");
print("%s\n", s1);

Comparing strings and length of a string: strcmp(), strlen()

Sample code:


#include <iostream>
using namespace std;

int main()
{
  cout << "two strings:" << endl;
  string s1, s2;
  cin >> s1 >> s2;

  if ( s1 > s2 ) 
    cout << s1 << " > " << s2 << endl;
  else if ( s1 < s2 ) 
    cout << s1 << " < " << s2 << endl;
  else
    cout << s1 << " = " << s2 << endl;


  cout << "length of s1=" << s1.length() << endl;

  return 0;
}

#include <stdio.h>
#include <string.h>

int main()
{
  printf("two strings:\n");
  char s1[128], s2[128];
  scanf("%s%s", s1, s2);

  if ( strcmp(s1, s2) > 0 )
    printf("%s > %s\n", s1, s2);
  else if ( strcmp(s1, s2) < 0 )
    printf("%s < %s\n", s1, s2);
  else
    printf("%s = %s\n", s1, s2);

  int len = strlen(s1);
  printf("length of s1=%d\n", len);

  return 0;
}
$ ./a.out
two strings:
alice bob
alice < bob
length of s1=5

$ ./a.out
two strings:
bob alice
bob > alice
length of s1=3

$ ./a.out
two strings:
alice alice
alice = alice
length of s1=5

Mandatory Practice Problem

Write a C program that reads data.txt containing strings and prints them out in reverse and the maximum string. For example, consider the following file data.txt
8
this function returns a length of string s 
$ ./a.out
s
string 
of 
a 
length
returns 
function
this
maximum = this
Solution

Practice Problems

  1. Write a C program solution to read n numbers from a user and print them in reverse:
    $ ./a.out
    How many? 5
    5 3 9 2 3
    3 2 9 3 5
  2. Write a C program solution that reads the file format numbers.txt into an array. Then compute the average and find the max. Yes, this can be done without an array, but use an array for practice:
    $ ./fileread
    Average is 34.850000
    Max is 94
  3. Read firstname and lastname, and prints out lastname, firstname with letters capitalized.
    $ ./name
    Alan Turing
    TURING, ALAN
    See a program solution.