Hi to all stackoverflow users. I am trying to build a simple (as an exercise) code that will read from a file and will store the words from a file in an dynamically allocated array. I think I am mallocing wrong. Does anyone see what I am doing wrong?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#define ARRSIZE 10
int main(){
char * myArray = malloc(ARRSIZE*sizeof(char*));
FILE * p1File;
char mystring1 [100];
char word [100];
int j = 0;
p1File = fopen ("my1file.txt","r");
if (p1File == NULL) perror ("Error opening file");
else{
while(fgets(mystring1, 100, p1File)){
int nuRead = sscanf(mystring1, "%s", word);\
printf("lepo ani magia\n\n");
if (nuRead > 0){
strncpy (*myArray[j], mystring1, 100);
//*myArray[j] = mystring1;
}
j += 1;
}
}
}
///////////////////////////////////
my text file is
this
will
probably
work
but
I
am
You're not allocating space for your strings, just the array of strings. myArray[j]
is just an uninitialized pointer. Instead, allocate space for each string in myArray
like so:
char *myArray[ARRSIZE]; // No reason for this to be dynamic.
// ...
if (nuRead > 0)
{
myArray[j] = malloc((strnlen(mystring, 100) + 1) * sizeof(char));
strncpy (myArray[j], mystring1, nuRead + 1);
}
As user411313 pointed out, sscanf doesn't return the number of characters matched, but the number of input items matched. Use strnlen
(or strlen
if you don't have strnlen
) to get the size of the string (and don't forget to add 1 for the null terminator).