0

这是我使用malloc()and编写的第一个程序free()。它对我来说看起来是正确的,当我参考我的书时,它看起来与书中的示例非常相似。但是,当我运行程序时,我会收到(lldb)提示。

例如,我输入 8 作为元素数,输入 2 作为初始化值。我的 xcode 编译器回复“(lldb)”。

谁能引导我朝着正确的方向前进?

#include <stdio.h>
#include <stdlib.h>
int * make_array(int elem, int val);
void show_array(const int ar[], int n);
int main(void)
{
int *pa;
int size;
int value;

printf("Enter the number of elements: ");
scanf("%d", &size);
while (size > 0) {
    printf("Enter the initialization value: ");
    scanf("%d", &value);
    pa = make_array(size, value);
    if (pa)
    {
        show_array(pa, size);
        free (pa);
    }
    printf("Enter the number of elements (<1 to quit): ");
    scanf("%d", &size);
}
printf("Done.\n");
return 0;
}

int * make_array(int elem, int val)
{
int index;
int * ptd;

ptd = (int *) malloc(elem * sizeof (int));

for (index = 0; index < elem; index++)
    ptd[index] = val;

return ptd;
}

void show_array(const int ar[], int size)
{
int i;
for (i = 0; i < size; i++)
    printf("%d",ar[i]);
}
4

1 回答 1

0

您的程序编译并运行(可能如您所料)。这是示例输出:

Enter the number of elements: 5
Enter the initialization value: 12
1212121212
Enter the number of elements (<1 to quit): 8
Enter the initialization value: 2
22222222
Enter the number of elements (<1 to quit): 100
Enter the initialization value: 34
34343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434343434
Enter the number of elements (<1 to quit): -1
Done.
于 2013-03-20T00:36:10.590 回答