...

/

Discussion: String Construction

Discussion: String Construction

Execute the code to understand the output and gain insights into string manipulation.

Run the code

Now, it's time to execute the code and observe the output.

Press + to interact
#include <stdio.h>
int main()
{
char filename[] = "update.txt";
char name[16];
int x;
/* initialize the name[] buffer with dots */
for( x=0; x<16; x++ )
name[x] = '.';
/* extract first part of the filename */
x = 0;
while( filename[x] != '.' ) {
name[x] = filename[x];
x++;
}
/* output result */
printf("Extracted name '%.16s' from '%s'\n", name, filename);
return(0);
}

Understanding the output

The code extracts the first part of a filename, before the extension. But it fails:

Extracted name 'update..........' from 'update.txt'
Code output

String termination is crucial

This point is to drive home the importance of properly terminating strings you create. In the code, the first part of the filename is extracted and saved in a buffer—but without adding the \0 (null ...