Strings in buffers


Buffer example: The program on the left below shows two separate buffers, and shows the construction of a string with index notation in the first buffer (in blue), and the construction of a string using pointer arithmetic notation in the second buffer (in red). One could also use pointer notation without the pointer arithmetic, but that is not shown below.

Notice that it is not necessary to stick consistently with index notation, or with pointer notation, but the two notations can be intermingled in the same calculation. (But you can't do pointer arithmetic on buff1, since it is a constant.) Such intermingled code is shown in the two example programs at the middle and right.

Use of buffers: buffers.c buffers2.c buffers3.c
#include <stdio.h>
#include <stdlib.h>
   
int main() {
   char buff1[100];
   char *buff2 = (char *) malloc(100);
   char *buff2_save = buff2;
   char ch;
   int i = 0;
   while ((ch = getchar()) != '\n') {
      /* insert into each buffer */
      buff1[i++] = ch;
      *(buff2++) = ch;
   }
   buff1[i] = '\0';
   *(buff2) = '\0';
   printf("\"%s\"\n", buff1);
   printf("\"%s\"\n", buff2_save);   
}
#include <stdio.h>
#include <stdlib.h>
   
int main() {
   char *buff = (char *) malloc(100);
   char ch;
   int i = 0;
   while ((ch = getchar()) != '\n') {
      /* insert into each buffer */
      buff[i++] = ch;
   }
   buff[i] = '\0';
   /*  can't use *(buff) = '\0'; */
   printf("\"%s\"\n", buff);  
#include <stdio.h>

   
int main() {
   char buff[100];
   char *buffp = buff;
   char ch;
   int i = 0;
   while ((ch = getchar()) != '\n') {
      /* insert into each buffer */
      *(buffp++) = ch;
   }
   *(buffp) = '\0';
   printf("\"%s\"\n", buff);
}
% cc -o buffers buffers.c
% buffers
Now is the time
"Now is the time"
"Now is the time"
% cc -o buffers2 buffers2.c
% buffers2
Now is the time
"Now is the time"

% cc -o buffers3 buffers3.c
% buffers3
Now is the time
"Now is the time"

When I first wrote the code on the left above, I didn't have the extra variable buff2_save. However, the pointer arithmetic using buff2++, ends up with this pointer pointing to the null character at the end of the string inside the second buffer. Thus the pointer arithmetic version trashes the pointer, so that it is necessary to save a copy of the pointer first.


Copyright © 2011, Neal R. Wagner. Permission is granted to access, download, share, and distribute, as long as this notice remains.