• Welcome to Powerbasic Museum 2020-B.
 

News:

Forum in repository mode. No new members allowed.

Main Menu

ProgEx10

Started by Frederick J. Harris, November 06, 2009, 03:32:34 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Frederick J. Harris


/*
   The last program was intended to be pretty much 'bad news'.  I wanted to let
   you know that C isn't very much like BASIC.  You never had to do anything
   like that in a BASIC program to assign a string to a variable.  In the Basic
   family of languages you just assign a string to a variable without having to
   mess around with such subtleties as where the memory for the string was
   coming from.  Further, in basic if you want to concatenate two or more
   strings together you just did something like str1 + str2 and the language did
   all the 'dirty' work behind the scenes.  Not so in C.  You do all the dirty
   work yourself, and it gets real dirty.  Next program shows low level string
   concatenation at work in C.  You know, we're just a hair above assembly
   language level at this point.  These C string minipulation functions - though
   slow and awkward to use - are lightening fast.  They are just thin wrappers
   on the asm string primitives that can really blast bytes around in memory.
   That's why C is sometimes referred as a 'high level assembler'.  So anyway,
   let's do a little C string concatenation.
*/

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

int main()
{
char* pszStr1="Frederick ";
char* pszStr2="John ";
char* pszStr3="Harris";
char* pName=NULL;
int iLen;

iLen = strlen(pszStr1) + strlen(pszStr2) + strlen(pszStr3) + 1;
pName=(char*)malloc(iLen);
if(pName)                         //1st find # of bytes you need for whole
{                                 //string plus null terminator.  Then use
    strcpy(pName,pszStr1);         //malloc() to get the bytes.  Next use
    strcat(pName,pszStr2);         //strcpy to copy 1st string to offset zero
    strcat(pName,pszStr3);         //of allocated memory.  Then finally use
    printf("pszName=%s\n",pName);  //strcat to concatenate the bytes together
    free(pName);                   //of the remaining strings.  If you don't
}                                 //free() allocated memory when you are done
else                              //with it your program has a 'memory leak'.
    puts("Memory Allocation Failure!");          //(that's bad!)
getchar();
             
return EXIT_SUCCESS;
}

/*       --Output--

pszName=Frederick John Harris

*/