Reputation: 31
I was doing some testing for a program of mine and was wondering why the program was crashing when entering my function. Don't mind the logic of the program, since i was still in the phase of making sure i understood how to use my tools at hand.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Constants */
#define HEX_CAPITAL_LETTERS_BEGIN 65
#define HEX_CAPITAL_LETTERS_END 90
#define HEX_NUMBERS_BEGIN 48
#define HEX_NUMBERS_END 57
#define EXIT_SUCCES 0
/* Prototypes */
void codeToField(char *charArray, int i, int hexFloor, int hexCeil, char *outputArray);
/* Main Function */
int main(void) {
char *code, warehouse, product, qualifiers;
int i = 0;
printf("Enter a MMOC product code: ");
scanf("%s", &code);
codeToField(code, i, HEX_CAPITAL_LETTERS_BEGIN, HEX_CAPITAL_LETTERS_END, &warehouse);
codeToField(code, i , HEX_NUMBERS_BEGIN, HEX_NUMBERS_END, &product);
strcpy(&qualifiers, code + i);
printf("\n\nWarehouse: %s\nProduct: %s\nQualifiers: %s\n", &warehouse, &product, &qualifiers);
return EXIT_SUCCES;
}
void codeToField(char *charArray, int i, int hexFloor, int hexCeil, char *outputArray) {
int j = 0;
while (charArray[i] >= hexFloor && charArray[i] <= hexCeil) {
outputArray[j] = charArray[i];
i++;
j++;
}
}
Thanks in advance.
Upvotes: 0
Views: 46
Reputation: 5877
The reason is because code
has no memory allocated to it. It is an uninitialized pointer. Try this instead:
// ...
char myString[16], *code, warehouse, product, qualifiers;
code = &myString[0];
int i = 0;
printf("Enter a MMOC product code: ");
scanf("%15s", code);
// ...
Upvotes: 0
Reputation: 12057
First, this does not do what you want:
char *code, warehouse, product, qualifiers;
The only pointer is code
, the other are just a single char
. You're printing them as strings with printf
, and you use warehouse
and product
as outputArray
in your function. They need to be pointers (or arrays) too:
char *code, *warehouse, *product, *qualifiers;
Then you need memory. The pointers are still uninitialized, so any reading from them is undefined behavior.
You can either allocate memory with automatic storage duration (on the stack) or dynamically (on the heap).
Stack:
char codestr[100];
code = codestr;
but then, you could also just have declared code
as
char code[100];
to avoid to have two variables.
If you want to allocate the memory dynamically, you would use malloc
:
code = malloc(100);
Don't forget to free the memory again:
free(code);
warehouse
, product
, qualifiers
all need memory too. Some of the array sizes could be deduced form the defined constants.
Upvotes: 1
Reputation: 10064
char *code, warehouse, product, qualifiers;
int i = 0;
printf("Enter a MMOC product code: ");
scanf("%s", &code);
Here, code
is an uninitialized pointer to memory so once you do the scanf
call, your program is hosed.
I think you want something more like
char code[100];
printf ("Enter a MMOC product code: ");
scanf ("%s", code);
Upvotes: 0