[英]What are the disadvantages of declaring an array of pointers to strings in 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.