Reputation: 31
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. I'm using 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;
}
}
Upvotes: 0
Views: 61
Reputation: 73366
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.
PS: What should main() return in C and C++? int
.
Upvotes: 0