429,251 Members | 2,727 Online
Need help? Post your question and get tips & solutions from a community of 429,251 IT Pros & Developers. It's quick & easy.

# Newbie. Microsoft Visual Express 2008. Problem with Assignment

 P: n/a // This will be a simple example for Matlab programming in C // But I have to first test the C program before I incorporate it into Matlab char *encrypt_string (char *string) { unsigned int i; // Allocate memory char *encrypted_string = (char *) malloc(strlen(string)*sizeof(char)); // Encrypt the string for (i = 0; i < strlen(string); ++i) { encrypted_string[i] = encrypt_char(string[i]); } encrypted_string[i] = "\0"; <------------- Something goes wrong warning C4047 return encrypted_string; } ------------------Anzahl der Dereferenzierungen bei 'char' und 'char [2]' unterschiedlich Jun 27 '08 #1
3 Replies

 P: n/a In article , encrypted_string[i] = "\0"; <------------- Something goes wrong encrypted_string[i] = '\0'; OR encrypted_string[i] = 0; "\0" is a string, which devolves to a pointer to the string, so you are trying to store a pointer in a char. -- "The first draught serveth for health, the second for pleasure, the third for shame, the fourth for madness." -- Sir Walter Raleigh Jun 27 '08 #2

 P: n/a On Thu, 24 Apr 2008 15:26:48 -0700 (PDT), Ha****************@web.de wrote: >// This will be a simple example for Matlab programming in C// But I have to first test the C program before I incorporate it intoMatlabchar *encrypt_string (char *string){ unsigned int i; // Allocate memory char *encrypted_string = (char *)malloc(strlen(string)*sizeof(char)); // Encrypt the string for (i = 0; i < strlen(string); ++i) { encrypted_string[i] = encrypt_char(string[i]); } encrypted_string[i] = "\0"; <------------- Something goes wrongwarning C4047 return encrypted_string;} The syntax error is because you should have used single quotes(') instead of double quotes("). However, after that is fixed, the statement invokes undefined behavior because you did not malloc enough space. strlen(string)*sizeof(char) evaluates to enough bytes to hold the encrypted data except for the terminal '\0'. You need to add one to the expression to make room for the '\0'. Remove del for email Jun 27 '08 #3

 P: n/a Ha****************@web.de wrote: > char *encrypt_string (char *string) { unsigned int i; // Allocate memory char *encrypted_string = (char *) malloc(strlen(string)*sizeof(char)); Casting the return value of malloc in C is generally considered to be a bad idea. Be sure to #include

### This discussion thread is closed

Replies have been disabled for this discussion.