user3879626
user3879626

Reputation: 127

array of strings with pointers in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char **pps;

    int i, n = 10;

    char name[256];

    pps = (char **)calloc(n,sizeof(char **));

    for (i=0; i<n; i++)
    {
        printf("\n Enter name[%d]: ",i+1);
        gets(name);
        printf("\n Name=%s len=%d",name,strlen(name)+1 );

        pps[i] = (char *)malloc(strlen(name)+1);
        printf("\n pps[i]=%u",pps[i]);
        if (pps[i] = NULL)
        {
            perror("\nerror in malloc");
            exit(1);
        }

        printf("\n pps[i]=%u",pps[i]);
        strncpy(pps[i],name,strlen(name)+1);
    }

}

/* input/output from program: Enter name[1]: abcdef

 Name=abcdef len=7
 pps[i]=13311184
 pps[i]=0

*/

The program gives Runtime Error ??? Please help to find what is wrong and why PPS[i] become currupted ??? I am using visual studio 2010

Upvotes: 1

Views: 439

Answers (1)

Your problem is here:

if (pps[i] = NULL)

It should be:

if (pps[i] == NULL)

Remember that = is an assignment operator while == is comparation

Also remember to use free at the end of your program to avoid memory leak.

Upvotes: 4

Related Questions