Re: newbie program, pointers again...



On Wed, 15 Mar 2006 20:21:16 +0100, "Martin Joergensen"
<unoder.spam@xxxxxxxxxxxx> wrote:


It works now, so I think I'll just stick to that unless somebody
has any really great idea that I didn't see.

- - - --
#include <stdio.h>
#include <math.h>
#include <ctype.h>

You don't need these two.

#include <stdio.h>

This is a duplicate.

#include <stdlib.h>
#include <string.h> // for memcpy

Except that you don't use memcpy in your program. But you do need it
for strlen and strcpy.


void repeat(char **dest_array, const char ch, const int n);
void add_text(char **dest_array, const char *source_array);

//////////////
int main()
{
char *char_ptr; /* pointer to beginning of char (array) */
char *destination_arr;

FILE *outputfile;
unsigned long size = 1600*sizeof(char); /* space for 20 lines
*/

char_ptr = malloc(size);
if (!char_ptr)
{
fprintf(stderr, "%s: line %d, malloc(%lu) failed.\n",
__FILE__, __LINE__, size);
exit(EXIT_FAILURE);
}

destination_arr = char_ptr;

printf("sizeof(char) = %i byte(s)\n", sizeof(char) );

sizeof evaluates to a size_t. A size_t is unsigned but need not be
int. For example, it could be unsigned long. %i is the wrong code
for unsigned anything. If you compiler doesn't support the z modifier
for %u then you should cast the value to match your format.

printf("\nPointer values:\n");
printf("char_ptr = %15p\n", char_ptr);

%p requires a void*. Since a char* is guaranteed to look like a
void*, this is probably not a problem. However it would be a good
habit to get into.


add_text(&destination_arr, "Howdy! ");
add_text(&destination_arr, "You crazy dumb computer!");
add_text(&destination_arr, "I really hate you!");
repeat(&destination_arr, '*', 10);
add_text(&destination_arr, "You stink, go away!");
repeat(&destination_arr, '-', 20);

if ( (outputfile=fopen("result.txt", "w") )==NULL)
{
printf("\nError opening output-file:
\"result.txt\".\n\n");
}
else
{
fprintf(outputfile, "%s", char_ptr);
}

printf("%s", char_ptr);
fclose(outputfile);
system("PAUSE");
return 0;
}


* functions */


void add_text(char **dest_array, const char *source_array)
{
sprintf(*dest_array, ("%s", source_array) );

printf("strlen(source_array) = %i\n", strlen(source_array) );
*dest_array += strlen(source_array);

Why compute strlen twice?

}

void repeat(char **dest_array, const char ch, const int n)
{
int i; /* local variable: counter */

for(i=0; i<n; i++) (*dest_array)[i] = ch;

memset is probably a little more efficient.


(*dest_array)[n] = '\0'; /* terminate string */

*dest_array += n; /* update position */
}


Best regards / Med venlig hilsen
Martin Jørgensen


Remove del for email
.



Relevant Pages