My program hangs while running a piece of code that uses this array. Unfortunately, I cannot describe everything here, because very big piece of code.

I have a structure:

struct element { char *one; char *two; }; 

Next comes an array of such structures (statically declared):

 struct element array[] = { {"1 field", "2 field"}, {"3 field", "4 field"}, {"5 field", "6 field"} }; 

On the one hand, the array is declared statically - why allocate memory. On the other hand, the structure fields are pointers (memory is allocated for pointers, not strings).

Is there a mistake here?

  • Specify, hangs or falls ? If it still hangs, i.e. does not wait for input and does not end, then most likely an infinite loop somewhere (for example, in some of the conditions, by mistake, instead of a == b filled) and the error in the question has no relation to it. - avp

2 answers 2

Is there a mistake here?

There is no error here, but there is a suspicious moment.

Assigned pointers lead to constant strings, which means that you cannot change characters within strings. First, it is not known whether the compiler has combined strings, that is, several structures can get the same pointers if the strings are different. Secondly, the memory area with these strings is most likely marked as readonly.

  • In theory, the program should not change the lines, and the code does not change them. And how to check, whether the compiler combined them? How to test possible problems? - Maxim Gusev
  • @MaximGusev, compare pointers to equality. But why, if nowhere is an attempt to change them? - Qwertiy
  • Well, if the structures are all different, then the pointers cannot be alone for different structures, then, at least I think so ... - Maxim Gusev
  • @MaximGusev, not structures, strings. In the example, you use 2 different lines 3 times each - the compiler will probably allocate memory only for 2 lines (and not 6) and place identical pointers in all 3 structures. - Qwertiy
  • @MaximGusev, yes: ideone.com/jgFu1H - Qwertiy

But you have already allocated a memory - after all, these lines are located somewhere :)

So everything is in order, nothing more needs to be allocated.

Another thing is that these lines, although C formally permits changing (for example, changing individual characters to others), it is strongly not recommended to do so.

  • Thank you, it means the error is not here. - Maxim Gusev
  • You are not trying to change them? Are they used as constant? - Harry
  • I don't need to change them. Yes. The program does not change them. - Maxim Gusev
  • Then the error is not there. - avp
  • one
    @Harry: "C formally allows me to change" - where did you get that from? The Plaintext language prohibits changing string literals, in the sense that attempting a change leads to undefined behavior. - AnT