O'Reilly logo

C by Nikolaos D. Tselikas, George S. Tselikis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 17

Review Exercises

17.1 Write a program that reads its command line arguments and allocates memory to store them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *tot_str;
int i, tot_chars;
if(argc == 1)/* Check if there is only one argument. */
{
printf("Missing arguments…\n");
exit(1);
}
tot_chars = 0; /* It counts the characters of all arguments. */
for(i = 1; i < argc; i++)/* Remember that argv[1] points to the first argument, argv[2] to the second one, and so forth. argv[0] points to the name of the program. */
tot_chars += strlen(argv[i]);
tot_str = (char *) malloc(tot_chars+1); /* Allocate an extra place for the null character. */
if(tot_str == NULL)
{
printf("Error: Not available ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required