Stack Exchange
Printing the value of pointer to char in C
I have this code:
main() {

    printf("enter the number of names: ");
    int n;
    scanf("%d", &n);
    getchar();

    char *p;
    p = malloc(n*LEN*sizeof(char));

    char *name = malloc(LEN*sizeof(char));

    int i;
    for(i = 0; i < n; i++) {
        gets(name);
        strcpy((p + i), name);
        printf("%s \n", (p + i));
        strncpy(name, "", LEN);
    }

    for(i = 0; i < n; i++) 
        printf("%s\n", (p + i));

}

and I have trouble with printing the values of pointer p which is correct in the first loop but in the second loop the output is wrong.(LEN has defined as 15). Where is the problem?

p must be of type char**

What is p + i?

p = malloc(n * sizeof(char*));

The purpose of this code is unclear. Separate it out into functions and it will be far easier to understand.

@purec I can't use pointer to pointer. and if p has to change why the first loop's output is correct?

@doctorlove p is a pointer to a 2d array and p + i is the ith row of the array

then what do you want?

p (and p+i) is a pointer to a char

What is your platform? gets has been deprecated long time ago

@purec I have to read some names from input and do something with them. but in this step I can't read input.

use this at least: char* p[n];

or even this: char arr[n][LEN];

gets is dangerous and obsolete. Use something else like fgets or getline

@Basile Starynkevitch, all his program is dangerous.

Compile with all warnings and debug info, so gcc -Wall -Wextra -g if using GCC. Improve the code to get no warnings. Read How to debug small programs. Learn to use valgrind and the GDB debugger. And provide some [MCVE] in your question

Assuming LEN is the maximum string length, you allocated a big chunk of memory in which you want to put strings.
Then the ith string you should put at strcpy((p + i*LEN), name);
You should also take care the string is not too long and is terminated, so better use
    strncpy((p + i*LEN), name, LEN-1);
    *(p+i*LEN-1)= '\0';


In this code
char *p;
p = malloc(n*LEN*sizeof(char));

char *name = malloc(LEN*sizeof(char));

int i;
for(i = 0; i < n; i++) {
    gets(name);
    strcpy((p + i), name);
    printf("%s \n", (p + i));
    strncpy(name, "", LEN);
}

you have a single char array, and put a "string" into the beginning when i is 0, e.g. "Hello".
When i is 1, if you use "world" as the next name, that's put into p[1], so p[0] is still 'H', giving you 'HWorld'.
You need a char ** and malloc each char * inside th loop.
(Don't forget to free what you malloc later) 
