c - 未打印指针字符串的第一个字符
问题描述
我正在尝试为长度未知的字符串分配动态内存(我正在尝试模拟编译问题)但是当我这样做时,我的 printf 不会从第二次执行中打印第一个字符。我正在使用 gcc 5.something。我附上了输出的屏幕截图。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main (){
//VARIABELS
//Input bitstream as a string
char *stringInput;
//No of inputs
int dataCount;
//memory size to allocate to array
int dataSize;
//FILE pointer
FILE *fptr;
//Loop count
int i;
//Binary declarations
long num, decimal_num, remainder, base = 1, binary = 0, noOf1 = 0;
//MEMORY ALLOCATION
//Enter N
printf("Enter N (the number of inputs):\n");
scanf("%d",&dataCount);
//+1 for comma (,) characters
dataSize = ((sizeof(int)+1)* dataCount);
//Initialize pointer allocated memory
stringInput = malloc(dataSize);
if (!stringInput)
{
perror("Error allocating memory");
abort();
}
memset(stringInput, 0, dataSize);
//Scan the numbers + TEST
scanf("%s",stringInput);
//Initialize file pointer
fptr = fopen("inputString.txt","w");
fprintf(fptr,"%s",stringInput);
free(stringInput);
//DECIMAL CONVERSION
while (num > 0){
remainder = num % 2;
//Calc no of 1's
if (remainder == 1)
noOf1++;
//Conversion
binary = binary + remainder * base;
num = num / 2;
base = base * 10;
}
}
解决方案
改变这个:
dataSize = ((sizeof(int)+1)* dataCount);
对此:
dataSize = ((sizeof(char) + 1) * (dataCount + 1));
因为你想存储一个字符串,而不是一个数字。
请注意最后+1
使用的 I,它用于字符串 NULL 终止符。
PS:在 C 和 C++ 中 main() 应该返回什么? int
.
推荐阅读
- reactjs - react-router - 无法在 this.props.location 中获取信息
- javascript - 为什么 event.preventDefault() 能够阻止子元素的默认浏览器行为?
- c# - 便携库 ObservableCollection 绑定错误
- python - 有没有更好(更有效)的方法从元组中删除项目?
- javascript - 使用 javascript 提取所有 css 选择器
- html - 如何覆盖嵌套 HTML 文档中的 CSS?
- c++ - 卡住 LNK1328:缺少字符串表
- angular - 更新服务值时在组件上运行功能(Angular 6)
- angular - 角度 7.0 pwa 服务人员未加载 css 文件
- git - 如何在未暂存的更改和旧代码之间切换?