it is my understanding that once a pointer is initialized to a string constant, the string cannot be modified. I've tried performing the modification and the program crashes.
This theory is given at Chapter 5.5 "Character Pointers and Functions" in The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie.
However there is an example of storing pointers in arrays (Chapter 5.6) where the contents of the pointer is modified. The program is as given below:
#include <stdio.h>
#include <string.h>
#define MAXLINES 5000 /* max #lines to be sorted */
#define MAXLEN 1000
char *lineptr[MAXLINES]; /* pointers to text lines */
char *alloc(int);
int readlines(char *lineptr[], int nlines);
int getline(char *, int);
void writelines(char *lineptr[], int nlines);
main()
{
int nlines; /* number of input lines read */
if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
writelines(lineptr, nlines);
return 0;
} else {
printf("error: input too big to sort\n");
return 1;
}
}
/* readlines: read input lines */
int readlines(char *lineptr[], int maxlines)
{
int len, nlines;
char *p, line[MAXLEN];
nlines = 0;
while ((len = getline(line, MAXLEN)) > 0)
if (nlines >= maxlines)
return -1;
else {
line[len-1] = '\0'; /* delete newline */
strcpy(p, line);
lineptr[nlines++] = p;
}
return nlines;
}
/* writelines: write output lines */
void writelines(char *lineptr[], int nlines)
{
int i;
for (i = 0; i < nlines; i++)
printf("%s\n", lineptr[i]);
}
int getline(char s[],int lim)
{
int c, i;
for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
The program does not show any warning or error when compiled but crashes after feeding the first line.
Can you please confirm if this is due to modification of a string constant initialized to a pointer? The pointer in question is @ line 28 "char *p" and strcpy performed on it @ line 35. Thank you.