关于内存使用情况,程序有什么问题?malloc多次使用同一指针时会发生什么?它是否每次都在堆中创建新内存,指针将指向新内存,旧内存将被浪费?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *ptr;
ptr = malloc(sizeof(int));
*ptr = 111;
ptr = malloc(sizeof(int));
*ptr =-234;
printf(“\n%d\n”, *ptr);
free(ptr);
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud) char filename[100];
char *file;
fgets(filename,100,stdin);
file =&filename;
Run Code Online (Sandbox Code Playgroud)
发出此警告:
warning: assignment from incompatible pointer type [enabled by default]
file =&filename;
Run Code Online (Sandbox Code Playgroud)
是不是&文件名和文件与字符的地址具有相同的类型,因为我使用&来获取变量的地址?
我正在学习C编程的基础知识,并发现它非常奇怪和困难.特别是与动态内存分配,指针和类似的东西.我发现了这个功能,并不太明白它有什么问题.
char *strdup(const char *p)
{
char *q;
strcpy(q, p);
return q;
}
Run Code Online (Sandbox Code Playgroud)
我想我必须使用malloc和free q.但功能"返回q".这是否意味着它会将q值存储在自己的内存中.所以在执行函数后仍然保存数据?
什么时候适合使用malloc?到目前为止我理解的是,每当我需要在函数中声明的变量用于其他地方时,我必须malloc一个新变量.真的吗?还有其他需要malloc的情况吗?
我有一个与" instanceof" 相关的练习,我不太清楚如何使用它.这就是我想出的:
for(int i = 4; i < 6; i++){
int availSupply = part[i].stockLevel+part[i].getAvailForAssembly();
if(availSupply instanceof Integer){
System.out.println("Total number of items that can be supplied for "+ part[i].getID()+"(" + part[i].getName() + ": "+ availSupply);
}
}
Run Code Online (Sandbox Code Playgroud)
代码看起来很好,但是它出现了一个错误:
Multiple markers at this line
Incompatible conditional operand types int and Integer at: if(availSupply instanceof Integer){
Run Code Online (Sandbox Code Playgroud)
我不知道我做错了什么,这是唯一出现的错误.