#include<stdio.h>
#include<string.h>
main () {
char *line[5];
int i;
line[0] = "line 1";
line[1] = "line 2";
line[2] = "line 3";
line[3] = "line 4";
line[4] = "line 5";
char *p;
p=line[2];
//*p = *(p+2); //gives error as segmentation fault.
printf("\n coming here : %s",*line); //works fine
printf("\n coming here : %s",*line++); //gives error "invalid increment in main"
printf("\n coming here : %s",*(line+2)++); //error, i assumed it will work as *(line+2) is also a pointer
printf("%c",*(line[4]+1));//works, prints character 'i'
printf("%c",**(line+4));//segmentation error, i assumed it to print character 'l'
}
I was trying this program and faced few errors as I have mentioned in the comments beside each line of code.
with char *line[5] i was trying to achieve a array of pointers each pointer element of this array pointing to a string.
Please help me clarify what all I am doing wrong here. Thanks.
Edit 1:
I have included only part of the example, please see the writelines function. Rest of this example is pretty straight forward this did not include it.
#define MAXLINES 5000 /* max #lines to be sorted */
char *lineptr[MAXLINES]; /* pointers to text 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 || p = alloc(len) == NULL) 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)
{
while (nlines-- > 0)
printf("%s\n", *lineptr++); // this is where they are incrementing array, which you said is incorrect.
}
Edit 2:
main(int argc, char *argv[])
{
char *line[] = {"linawee 1", "lipe 2", "lint 3", "linr 4"};
while (--argc > 0) //command line input has same number of elements as 'line'
{
printf("%s%s", *++argv, (argc > 1) ? " " : ""); //works just fine.
printf("%s", *++line); //error
}
}
Please explain the above prog, why it works for one and gives error for other. Thanks.