簡體   English   中英

C中帶有指針的字符串數組

[英]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);
    }

}

/ *程序的輸入/輸出:輸入名稱[1]:abcdef

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

* /

該程序給出運行時錯誤 請幫助找出問題所在以及PPS [i]為何損壞? 我正在使用Visual Studio 2010

您的問題在這里:

if (pps[i] = NULL)

它應該是:

if (pps[i] == NULL)

請記住, =是賦值運算符,而==是比較

還請記住在程序末尾使用free以避免內存泄漏。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM