[英]1st character of pointer string not printed
I'm trying to allocate a dynamic memory for string which is of unknown length (im trying for a mock-compi question) but when i do that my printf wont print the first character from second execution. 我正在尝试为长度未知的字符串分配动态内存(我正在尝试模拟模仿问题),但是当我这样做时,我的printf不会从第二次执行中打印第一个字符。 I'm using gcc 5.something.
我正在使用gcc 5.something。 I've attached a screen shot of the output.
我已经附上了输出的屏幕截图。
#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;
}
}
Change this: 更改此:
dataSize = ((sizeof(int)+1)* dataCount);
to this: 对此:
dataSize = ((sizeof(char) + 1) * (dataCount + 1));
since you want to store a string, not a number. 因为您要存储字符串,而不是数字。
Notice the +1
I used at the end, which is for the string NULL-terminator. 请注意,我在末尾使用的
+1
是字符串NULL终止符。
PS: What should main() return in C and C++? PS: main()在C和C ++中应该返回什么?
int
. int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.