我需要使用C中的动态内存以字母顺序排列名称
目标是获取“n”个名称作为输入,并使用动态内存分配按字母顺序排列它们。如果我输入 4 个名字,代码就可以正常工作。但如果我输入超过 5 个名称,则代码会在我输入第五个名称后中断。即使我将 n 指定为 6,它也不接受第 6 个名称。 谁能告诉我原因吗?以及解决的办法呢? 代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char[], char[]);
int main()
{
char** name;
int i, n, j, y;
printf("Enter the number of names:");
scanf("%d", &n);
name = (char**)malloc(n * sizeof(char));
for (i = 0; i < n; i++)
{
name[i] = (char*)malloc(100 * sizeof(char));
}
printf("Enter the names:\n");
for (i = 0; i < n; i++)
{
scanf("%s", *(name + i));
}
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
y = strcmp(name[i], name[j]);
if (y >= 0)
{
swap(name[i], name[j]);
}
}
}
for (i = 0; i < n; i++)
{
printf("%s\n", name[i]);
}
return 0;
}
void swap(char a[], char b[])
{
char temp[20];
strcpy(temp, a);
strcpy(a, b);
strcpy(b, temp);
}
The goal is to get 'n' number of names as input and arrange them in alphabetical order using dynamic memory allocation. If i input 4 names the code is working fine. But if i input more than 5, the code cuts off after i enter the fifth name. It is not accepting the 6th name even if i give n as 6.
Can anyone tell me the reason why? And the solution to it?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char[], char[]);
int main()
{
char** name;
int i, n, j, y;
printf("Enter the number of names:");
scanf("%d", &n);
name = (char**)malloc(n * sizeof(char));
for (i = 0; i < n; i++)
{
name[i] = (char*)malloc(100 * sizeof(char));
}
printf("Enter the names:\n");
for (i = 0; i < n; i++)
{
scanf("%s", *(name + i));
}
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
y = strcmp(name[i], name[j]);
if (y >= 0)
{
swap(name[i], name[j]);
}
}
}
for (i = 0; i < n; i++)
{
printf("%s\n", name[i]);
}
return 0;
}
void swap(char a[], char b[])
{
char temp[20];
strcpy(temp, a);
strcpy(a, b);
strcpy(b, temp);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在此语句中,分配的内存的大小错误地指定了
您必须编写
交换函数通常不正确的。对于初学者来说,尚不清楚为什么使用魔术数20
,而分配的角色阵列的尺寸等于100。
您需要的只是交换指向字符串的指针。例如,可以按照以下方式声明和定义函数交换
,并像以下方式一样
,以使输入更安全。您应该
注意,当阵列不再需要时,您应该释放所有分配的内存。
In this statement the size of the allocated memory is specified incorrectly
You have to write
The swap function in general is incorrect. For starters it is unclear why there is used the magic number 20
while the allocated character arrays have sizes equal to 100.
What you need is just to swap pointers pointing strings. For example the function swap can be declared and defined the following way
and called like
Also to make the input safer you should write
Pay attention to that you should free all the allocated memory when the arrays will not required any more.