Thread: [c]Pointers
View Single Post
Old 12-21-2006, 09:23 PM   #6 (permalink)
Rekna
Junkie
 
Quote:
Originally Posted by zero2
Thank You Rekna. I liked the code that you had where you test for lowercase q or uppercase Q, that was something that I didn't think off.

I also ran into a problem, when I added the while loop, I wasn't able to ask the user the size of the pointer after the first iteration.

So my output looked like this:
=====First Time Run==========
Enter an estimate of size of string: 7
Enter a binary string to continue or q to quit:
123ab46
The given string is not convertible!
======Second Time Run==========
Enter a binary string to continue or q to quit: 7
123ab46
The given string is not convertible!

Here's my latest code, hopefully I'm doing something right here:

Code:
#include<stdio.h>
#include<stdlib.h>

void convertToBinaryVersionA();

int main(void)
{
	convertToBinaryVersionA();
		return 0;
}

void convertToBinaryVersionA()
{
	char *cPtr;
	int iSize;
	int i;
	char *cBinary;
	int j = 0;
	int iCount;
	
	printf("Enter an estimate of size of string: ");
	scanf("%d", &iSize);
	
	getchar();
	cPtr =  (char *) malloc (iSize * sizeof(char));
	printf("Enter a binary string to continue or q to quit: ");
	gets(cPtr);
	
	cBinary = (char *) malloc (iSize * sizeof(char));
	
	for (i = 0; i < iSize; i++)
		{
			if( * (cPtr + 0) == 'q' || * (cPtr + 0) == 'Q')
				{
					printf("Thank You!\n");
				}
			else if ( * (cPtr + i) == '0' || * (cPtr + i) == '1' )
				{
					cBinary[j] = cPtr[i];
					j++;
					iCount = 0;
				}
			else
				{
					iCount = 1;
					
				}
		}
		if ( iCount == 0 )
		{
			printf("The converted string is: %s", cBinary);
		}
		else
		{
			printf("The inputed string is not convertible!\n");
		}
	
	return;
}

Don't ask the user the size of the string, use input should always be kept to a minimum. Instead just create a buffer for the string that is bigger than a user would enter (say 1000 or 10000 characters). Asking the user what size the string is gives the user an unnecessary burden. In addition if the user is wrong and they make a string that is to small then your program will more than likely crash, or worse a malicious user could use that program to do bad things. There are lots of issues dealing with buffer overrun errors that you shouldn't worry about at this time. That is a much more advanced topic. For now just use a very large array that way you don't have to use malloc instead just use an array.

Also if and when you use malloc make sure you free the memory also. Failure to free it causes memory leaks.
Rekna is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37