4 c arrays pointers allocation
我尝试过使用tripple指针,但它仍然失败.码:
#include <stdlib.h>
#include <stdio.h>
int set(int *** list) {
int count, i;
printf("Enter number:\n");
scanf("%d", &count);
(*list) = (int **) malloc ( sizeof (int) * count);
for ( i = 0; i<count;i++ ) {
(**list)[count] = 123;
}
return count;
}
int main ( int argc, char ** argv )
{
int ** list;
int count;
count = set(&list);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的建议
你所谓的列表实际上是一个数组.您可以通过以下方式执行此操作:
#include <stdlib.h>
#include <stdio.h>
ssize_t set(int ** ppList)
{
ssize_t count = -1;
printf("Enter number:\n");
scanf("%zd", &count);
if (0 <= count)
{
(*ppList) = malloc(count * sizeof **ppList);
if (*ppList)
{
size_t i = 0;
for (; i < count; ++i)
{
(*ppList)[i] = 42;
}
}
else
{
count = -1;
}
}
return count;
}
int main (void)
{
int * pList = NULL;
size_t count = 0;
{
ssize_t result = set(&pList);
if (0 > result)
{
perror("set() failed");
}
else
{
count = result;
}
}
if (count)
{
/* use pList */
}
...
free(pList);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6633 次 |
| 最近记录: |