#include <stdio.h> #include <stdlib.h> int *fun() { int *tarshut; tarshut=(int*)malloc(9) for(i=0;i<9;i++) tarshut[i]=tarShut; return tarshut; } int main() { int *tarshut; int i; tarshut=fun(); for(i=0;i<9;i++) printf("tarshut[%d]=%d\n",i,tarshut[i]); free(tarshut); return 0; }
时间: 2024-04-12 15:29:54 浏览: 25
您的代码存在一些问题:
1. 在函数 `fun` 中,您忘记了声明变量 `i`。在 C 语言中,您必须在使用变量之前先声明它们。
2. 在 `fun` 函数中,您没有为 `malloc` 函数分配的内存指定大小。应该将 `malloc` 函数的参数设置为 `9 * sizeof(int)`,以便为 9 个整数分配足够的内存空间。
3. 在 `fun` 函数中,您在循环中错误地将 `tarShut` 赋值给 `tarshut[i]`。我假设 `tarShut` 是一个未定义的变量,您可能想将其更正为 `i`。
4. 在 `main` 函数中,您忘记了声明变量 `i`。
5. 在 `main` 函数中,您没有检查 `malloc` 函数是否成功分配了内存。如果 `malloc` 返回 `NULL`,则表示内存分配失败。
6. 在 `main` 函数中,您没有在释放内存后将指针设置为 `NULL`,这是一个良好的习惯。
以下是修正后的代码:
```c
#include <stdio.h>
#include <stdlib.h>
int *fun()
{
int *tarshut;
tarshut = (int*)malloc(9 * sizeof(int));
if (tarshut == NULL) {
printf("内存分配失败");
exit(1);
}
for (int i = 0; i < 9; i++) {
tarshut[i] = i;
}
return tarshut;
}
int main()
{
int *tarshut;
int i;
tarshut = fun();
for (i = 0; i < 9; i++) {
printf("tarshut[%d] = %d\n", i, tarshut[i]);
}
free(tarshut);
tarshut = NULL;
return 0;
}
```
修正后的代码将为 `tarshut` 数组分配了足够的内存空间,并且在释放内存后将指针设置为 `NULL`。循环中的 `tarshut[i]` 被更正为 `i`,以正确初始化数组中的元素。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)