动态内存分配 java_动态内存分配代码

我正在学习C(C)中的内存分配基础知识 .

#include "stdio.h"

#include "string.h"

#include "stdlib.h"

void main(){

char *str;

char *input;

int *ilist;

int i, size1, size2;

printf("Number of letters in word: ");

scanf("%d", &size1);

printf("Number of integers: ");

scanf("%d", &size2);

str = (char *)malloc(size1*sizeof(char) + 1);

ilist = (int *)malloc(size2*sizeof(int));

if (str == NULL || ilist == NULL){

printf("Lack of memory");

}

printf("Word: ");

int k = size1;

// the following line is done to prevent memory bugs when the amount of

letters in greater than size1.

scanf("%ks", &str); //I guess something is wrong with this line

/* user inputs a string */

for (i = 0; i < size2; i++) {

printf("Number %d of %d: ", i + 1, size2);

//this scanf is skipped during the execution of the program

scanf("%d", ilist + i);

}

free(str);

free(ilist);

system("pause");

}

程序要求用户写入单词中的字母数量和数字中的位数 . 然后用户写下这个词 . 然后他逐个写整数,具体取决于之前键入的数字 . 我遇到的问题是当用户写完整个单词时,跳过下一个scanf . 谢谢 . 附:在这段代码中可以有其他类型的内存错误吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值