【发布时间】:2016-04-15 15:03:18
【问题描述】:
我使用指针代替数组,我知道与数组不同,指针需要被释放。为什么使用指针代替数组会给我一个分段内存错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void bin(void){
char *input;
int choice;
int x = 0;
printf("Enter Decimal Code:\n");
scanf("%s",&input);
int leng = strlen(input);
for(int i = 0; i <= leng ; ++i){
if(input[i] == '1'){
x += pow(2,i);
}
else if(input[i] == '0'){
input[i] = 0;
}
free(input);
}
printf("Binary-Dec: %d\n",x);
}
int main()
{
bin();
}
【问题讨论】:
-
只有指向动态分配的数据块开头的指针才需要被释放。你的指针指向不好。所以你不能把它传递给
scanf。 -
@juanchopanza 我怎样才能通过 scanf/ 是否有替代方法
-
不要添加不同语言的标签。
-
@robinhood46 您需要弄清楚指针是什么(提示:名称中有线索)并且您需要阅读
scanf的一些文档(特别是它对您的指针的假设传递给它。)