简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM