0

I am writing a program which will store a list of file names as a string array. When I declare it as

char *filenames[1]

I have no errors... but when I do

char *filenames 

I get a few errors. Not at the declaration but in later use. for example when I do:

filenames[3]= (char*)malloc( strlen(line) + 1);//here ERROR is : Cannot assign char* to char.

But with the first declaration with [1] it is all fine. I was just wondering what is the difference between them?

Trust me I tried looking for the answer on google but can't find any good ones regarding this case.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
ITguy
  • 847
  • 2
  • 10
  • 25
  • Both are undefined behaviour. Please follow a beginners tutorial on C. Figure out what `filenames[3]= ...` means before using it. – juanchopanza Nov 04 '15 at 09:50

2 Answers2

1

At the outset, char *filenames represents a char * variable named filenames whereas, char *filenames[1] represents an array of char * variables, with one element.

From the point of the usage, both are same, but the major difference is, the first one has to be used as a normal variable and the second one can be indexed, as an array.

If you're in need to use only one variable, don't use an array. You may be in danger of using out of bound indexes if you're not careful enough.

Also, as a note, please see this discussion on why not to cast the return value of malloc() and family in C..

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Thank you that clears it up. I did not study computer science but I am working in IT now. So sometimes my basic knowledge can be a bit shaky. – ITguy Nov 04 '15 at 09:53
1

Relative to this statement

filenames[3]= (char*)malloc( strlen(line) + 1);//here ERROR is : Cannot assign char* to char.

the both declarations are wrong.

The firwt declaration

char *filenames[1]

is wrong because it declares an array of pointers to char having only one element. But in the statement with memory allocation there is used index 3. So there is an attempt to access memory beyond the array becuase the only valid index for an array that has one element is 0.

The second declaration

char *filenames 

is wrong because it does not declare an array of pointers. So applying the subscript operator for identifier filenames

filenames[3]

gives a scalar object of type char instead of a pointer of type char *

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335