0

Consider the following:

typedef struct wordType
{
    char word;
    uint count;
};

int main( void ) 
{
    typedef struct wordType * WORD_RECORD;
    WORD_RECORD arrayOfWords = malloc(10 * sizeof( WORD_RECORD) );

    FILE * inputFile;
    char temp[50];
    uint index;
    inputFile = fopen( "input.txt", "r"); 

    while( fscanf( inputFile, "%s", temp) == 1 )
        {
        printf("%s\n", temp );
        arrayOfWords[index].word = malloc( sizeof(char)*(strlen(temp) + 1 ));

        strcpy( arrayOfWords[index].word, temp );
    }
    index++;
}

I'm trying to malloc each time a word is taken in through scanf. However, I cannot seem to figure out why this does not work. I am getting errors:

warning: assignment makes integer from pointer without a cast

warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast
Busch
  • 857
  • 10
  • 29

2 Answers2

2

A c string is of type char*. When you say

char word;

you're making just enough space for one character, not the whole thing. Make word type char*:

char* word;

Don't forget to set count.

Additionally, you probably want to watch out that you never read more than 10 lines or you'll get another memory error.

Paul Rubel
  • 26,632
  • 7
  • 60
  • 80
  • That's my fault, I edited the code. It should (I hope) be an array of structs, of which I made. – Busch Apr 29 '13 at 21:49
  • Now when I set a loop to iterate through the array of structs and print out the word I am getting a segmentation fault. Is this due to the way I am trying to copy the word into the array? – Busch Apr 29 '13 at 21:53
  • strncpy would be a safer alternative to strcpy, particularly if you suspect an error. – Paul Rubel Apr 29 '13 at 22:04
  • No, `strncpy` would just give the possibility of failing to copy the nul terminator. @SeanHellebusch The only error in the code you have posted is the type of `word`. If you fixed that and still have problems, it might be worth posting the updated code as a new question. – simonc Apr 30 '13 at 00:15
  • If I'm reading in input that I don't control it makes sense to block it off as much as possible, hence the sprintf, with an added null as you mention. You'd also want to make sure the fscanf never gets a line of more than 50 characters. http://stackoverflow.com/questions/1621394/how-to-prevent-scanf-causing-a-buffer-overflow-in-c – Paul Rubel Apr 30 '13 at 12:06
1

You want to use word as a string. A string is a null-terminated array of chars so you need to give it type char*. Since you are dynamically allocating memory for each word, make sure to call free on each word later.

Alternatively, you could make use of the fact that temp is a 50 char array and hard code word to have a similar size.

One final, minor point, sizeof(char) is guaranteed to be 1 so you can simplify your malloc calculation.

simonc
  • 41,632
  • 12
  • 85
  • 103