87134

Structure Problem in C

My structure looks as follows:

typedef struct { unsigned long attr; char fileName[128]; } entity;

Then I try to assign some values but get an error message...

int attribute = 100; char* fileNameDir = "blabla....etc"; entity* aEntity; aEntity->attr = attributes; aEntity->fileName = fileNameDir;

Compiler tells me:

Error: #137: expression must be a modifiable lvalue aEntity->fileName = fileNameDir;

Why cant I assign here this character to the one in the structure?

Thanks

Answer1:

    <li>You're treating a char[] (and a char*, FTM) as if it was a string. Which is is not. You can't assign to an array, you'll have to copy the values. Also, the length of 128 for file names seems arbitrary and might be a potential source for buffer overflows. What's wrong with using std::string? That gets your rid of all these problems. </li> <li>You're defining a pointer to some entity, don't initialize it, and then use it as if at the random address it points to was a valid entity object. </li> <li>There's no need to typedef a struct in C++, as, unlike to C, in C++ struct names live in the same name space as other names. </li> </ul>

    If you absolutely must use the struct as it is defined in your question (it is pre-defined), then look at the other answers and get yourself "The C Programming Language". Otherwise, you might want to use this code:

    struct entity { unsigned long attr; std::string fileName; }; entity aEntity; aEntity.attr = 100; aEntity.filename = "blabla....etc";

    Answer2:

    You can't assign a pointer to an array. Use strncpy() for copying the string:

    strncpy( aEntity->fileName, fileNameDir, 128 );

    This will leave the destination not null-terminated if the source is longer than 128. I think the best solution is to have a bigger-by-one buffer, copy only N bytes and set the N+1th byte to zero:

    #define BufferLength 128 typedef struct { unsigned long attr; char fileName[BufferLength + 1]; } entity; strncpy( aEntity->FileName, fileNameDir, BufferLength ); *( aEntity->FileName + BufferLength ) = 0;

    Answer3:

    You should be copying the filename string, not changing where it points to.

    Answer4:

    Are you writing C or C++? There is no language called C/C++ and the answer to your question differs depending on the language you are using. If you are using C++, you should use std::string rather than plain old C strings.

    There is a major problem in your code which I did not see other posters address:

    entity* aEntity;

    declares aEntity (should be anEntity) as a pointer to an entity but it is not initialized. Therefore, like all uninitialized pointers, it points to garbage. Hence:

    aEntity->attr = attributes;

    invokes undefined behavior.

    Now, given a properly initialized anEntity, anEntity->fileName is an array, not a pointer to a character array (see question 6.2 in the C FAQ list). As such, you need to copy over the character string pointed to by fileNameDir to the memory block reserved for anEntity->fileName.

    I see a lot of recommendations to use strncpy. I am not a proponent of thinking of strncpy as a safer replacement for strcpy because it really isn't. See also Why is strncpy insecure?

    #include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct st_entity { unsigned long attr; char fileName[FILENAME_MAX + 1]; } entity; int main(void) { int status = EXIT_FAILURE; unsigned long attribute = 100; char *fileNameDir = "blabla....etc"; entity *anEntity = malloc(sizeof(*anEntity)); if ( anEntity ) { anEntity->attr = attribute; anEntity->fileName[0] = '\0'; strncat(anEntity->fileName, fileNameDir, sizeof(anEntity->fileName) - 1); printf("%lu\n%s\n", anEntity->attr, anEntity->fileName); status = EXIT_SUCCESS; } else { fputs("Memory allocation failed", stderr); } return status; }

    See strncat.

    Answer5:

    You're trying to use char* as if it was a string, which it is not. In particular, you're telling the compiler to set filename, a 128-sized char array, to the memory address pointed by fileNameDir.

    Use strcpy: http://cplusplus.com/reference/clibrary/cstring/strcpy/

    Answer6:

    You can't assign a pointer to char to a char array, they're not compatible that way, you need to copy contents from one to another, strcpy, strncpy...

    Answer7:

    Use strncpy():

    strncpy( aEntity->fileName, fileNameDir, sizeof(entity.fileName) ); aEntity.fileName[ sizeof(entity.fileName) - 1 ] = 0;

    The strncpy() function is similar, except that not more than n bytes of src are copied. Thus, if there is no null byte among the first n bytes of src, <strong>the result will not be null-terminated.</strong> See man page.

    Answer8:

    1) The line char* fileNameDir = "blabla....etc" creates a pointer to char and assigns the pointer an address; the address in this case being the address of the text "blabla....etc" residing in memory.

    2) Furthermore, arrays (char fileName[128]) cannot be assigned to at all; you can only assign to members of an array (e.g. array[0] = blah).

    Knowing (1) and (2) above, it should be obvious that <strong>assigning an address to an array is not a valid thing</strong> to do for several reasons.

    What you <strong>must do instead</strong> is to copy the data that fileNameDir points to, to the array (i.e. the members of the array), using for example strncpy.

    Also note that you have merely allocated a pointer to your struct, but no memory to hold the struct data itself!

    Answer9:

    First of all, is this supposed to be C or C++? The two are not the same or freely interchangeable, and the "right" answer will be different for each.

    If this is C, then be aware you cannot assign strings to arrays using the '=' operator; you must either use strcpy() or strncpy():

    /** * In your snippet above, you're just declaring a pointer to entity but not * allocating it; is that just an oversight? */ entity *aEntity = malloc(sizeof *aEntity); ... strcpy(aEntity->fileName, fileNameDir);

    or

    strncpy(aEntity->fileName, fileNameDir, sizeof aEntity->fileName);

    with appropriate checks for a terminating nul character.

    If this is C++, you should be using the std::string type for instead of char* or char[]. That way, you can assign string data using the '=' operator:

    struct entity {unsigned long attr; std::string fileName}; entity *aEntity = new entity; std::string fileNameDir = "..."; ... entity->fileName = fileNameDir;

    Answer10:

    The major problem is that you declared a pointer to a struct, but allocated no space to it (unless you left some critical code out). And the other problems which others have noted.

    Answer11:

    The problem lies in the fact that you cannot just use a pointer without initialising it to a variable of that same datatype, which in this is a entity variable. Without this, the pointer will point to some random memory location containing some garbage values. You will get segmentation faults when trying to play with such pointers.

    The second thing to be noted is that you can't directly assign strings to variables with the assignment operator(=). You have to use the strcpy() function which is in the string.h header file.

    The output of the code is: 100 blabla......etc

    #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { unsigned long attr; char fileName[128]; } entity; void main() { unsigned long int attribute = 100; char *fileNameDir = "blabla....etc"; entity struct_entity; entity *aEntity = &struct_entity; aEntity->attr = attribute; strcpy(aEntity->fileName, fileNameDir); printf("%ld %s", struct_entity.attr, struct_entity.fileName); }

    Answer12:

    For char fileName[128], fileName is the array which is 128 char long. you canot change the fileName. You can change the content of the memory that filename is pointing by using strncpy( aEntity->fileName, fileNameDir, 128 );

Recommend

  • Write extended file attributes
  • content-type validation with paperclip fails
  • Confusion in the output
  • Delphi Download File with WinInet with UserName and Password
  • Subtlety in conversion of characters to integers
  • programatically evaluating the value of somaxconn, to set the listen backlog parameter
  • iOS/Objective C: Converting RGB Data to UIImage
  • wchar_t is 2-bytes in visual studio and stores UTF-16. How do Unicode-aware applications work with c
  • Web Application and In-Memory State
  • Using replacements with a raw Sequelize query: avoiding single quotes?
  • Determine if UTF-8 encoded NSData contains a null-terminated string
  • Is Android development possible on netbooks? [closed]
  • How to resize image if the image is bigger than Textbox.But it not increase scale if smaller
  • Selection Sort, For Java
  • Google Maps api v3 get start and end coordinates of a street
  • What causes the runtime difference in this trivial fortran code?
  • Wrong labels when plotting a time series pandas dataframe with matplotlib
  • uniform generation of points on 3D box
  • What and where is mdimport
  • Should I or shouldn't I use the CachingConnectionFactory with hornetq 2.4.1
  • Alternative To body {overflow:scroll;} That Will Prevent Page Jostling/Wriggling?
  • Swift: Switch statement fallthrough behavior
  • How to test if a URL from an Eclipse bundle is a directory?
  • Sencha Touch 2.0 Controller refs attribute not working?
  • When to use `image` and when to use `Matrix` in Emgu CV?
  • What is the “return” in scheme?
  • Excel - Autoshape get it's name from cell (value)
  • Check if a string to interpolate provides expected placeholders
  • Which linear programming package should I use for high numbers of constraints and “warm starts” [clo
  • RestKit - RKRequestDelegate does not exist
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • Traverse Array and Display in markup
  • Linker errors when using intrinsic function via function pointer
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Load html files in TinyMce
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • coudnt use logback because of log4j
  • LevelDB C iterator
  • How can i traverse a binary tree from right to left in java?