473,915 Members | 5,914 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

NULL?? How come??

Hi all,

I have a the following simple piece of code which has taken me hours
to try and sort out the problem, but still unable to find what is
wrong.

void main( void )
{
char (*string)[20]; ............... ........(1)

string = malloc(10 * sizeof *string); .....(2)
string[0] = NULL; ............... ..........(3)
}

Basically, I am allocating memory to an array of strings of 20 chars
max, and setting element 0 of the array to be a NULL value.
Lines (1) to (2) work OK, but line (3) does not work. I wish to set
the string of element 0 to be a NULL value, but keeps getting an error
saying:

"left operand must be l-value"

Please help me, I dont understand what's wrong.

Thank you all in advance,
mike79
Nov 13 '05 #1
16 2417
On 3 Nov 2003 03:43:45 -0800, mi****@iprimus. com.au (mike79) wrote:
Hi all,

I have a the following simple piece of code which has taken me hours
to try and sort out the problem, but still unable to find what is
wrong.

void main( void )
{
char (*string)[20]; ............... ........(1)

string = malloc(10 * sizeof *string); .....(2)
/* set the first element of the array to an empty string */
if (string != NULL) {
string[0][0] = '\0';
}}
Basically, I am allocating memory to an array of strings of 20 chars
max, and setting element 0 of the array to be a NULL value.
Lines (1) to (2) work OK, but line (3) does not work. I wish to set
the string of element 0 to be a NULL value, but keeps getting an error
saying:

"left operand must be l-value"


Each element of the array has type (char [20]), array of 20 chars. You can't
assign to arrays! See the corrections to your code above

Nov 13 '05 #2
> I have a the following simple piece of code which has taken me hours
to try and sort out the problem, but still unable to find what is
wrong.

void main( void )
{
char (*string)[20]; ............... ........(1)

string = malloc(10 * sizeof *string); .....(2)
string[0] = NULL; ............... ..........(3)
}


Try
(*string)[0] = NULL;

--
runefv
Nov 13 '05 #3
On Mon, 3 Nov 2003 13:03:21 +0100, "Rune Flaten VÖrnes"
<re************ ******@remove.k ongsberg.remove .com> wrote:
I have a the following simple piece of code which has taken me hours
to try and sort out the problem, but still unable to find what is
wrong.

void main( void )
{
char (*string)[20]; ............... ........(1)

string = malloc(10 * sizeof *string); .....(2)
string[0] = NULL; ............... ..........(3)
}


Try
(*string)[0] = NULL;


Let's see. *string is of type (char [20]). **string (which is the same thing as
(*string)[0] and even *string[0] (in this case)) is of type (char). Why are you
assigning NULL to a char?

(as a side note, using NULL over 0 here is advantageous because the compiler
will catch the incorrect assignment (assuming NULL does not expand to just 0)
and possibly a bug in your reasoning).
Nov 13 '05 #4
mike79 wrote:
Hi all,

I have a the following simple piece of code which has taken me hours
to try and sort out the problem, but still unable to find what is
wrong.

void main( void )
it's int main(void) or int main(int argc, char **argv).
{
char (*string)[20]; ............... ........(1)
Not an expert, but I'm not sure the above is correct (any guru out there
?).

But well, let's pretend it is and it really means what you want...
string = malloc(10 * sizeof *string); .....(2)
string[0] = NULL; ............... ..........(3)
}
Basically, I am allocating memory to an array of strings of 20 chars
max, and setting element 0 of the array to be a NULL value.
Lines (1) to (2) work OK, but line (3) does not work. I wish to set
the string of element 0 to be a NULL value, but keeps getting an error
saying: "left operand must be l-value"
Please help me, I dont understand what's wrong.


<gurus, please correct me if I'm wrong>

This last line is basically the same as writing :
int main(void)
{
char str20[20];
str20 = NULL;
return 0;
}

This gives me (gcc 3.x, with -Wall -ansi -pedantic switches) :
'incompatible types in assignment'

This does not surprise me, since, while sharing some mechanisms, an
automatic array and a pointer to a dynamically allocated memory block
are two different things.

You can consider str20 as a pointer to the first element of a 20 chars
array (and yes it is, technically), but it's a 'read-only' pointer, in
the meaning that you *can not* modify the *address* it points to.

If what you want is to init each element in the 'string' array to the
empty string, you may want to have a look at calloc() or memset() :

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
char (*strings)[20];
int i;
int j;
size_t size = 10 * sizeof *strings;

strings = malloc(size);
memset(strings, 0, size);

for (i = 0; i < 10; i++) {
printf("strings[%d] : \n", i);
for (j = 0; j < 20; j++) {
printf(" '%c' ", strings[i][j] + '0');
}
printf("\n");
}

free(strings);
return 0;
}
Note that it *may* not be necessary (at least it *seems* not to be on
Linux with gcc 3.2.2 : commenting out the 'memset()' call doesn't seems
to change the output), but as this could be an UB, I would not rely on
this without the enlightening advices of some guru here (any guru around ?-)

HTH,
Bruno

Nov 13 '05 #5
mi****@iprimus. com.au (mike79) wrote:
I have a the following simple piece of code which has taken me hours
to try and sort out the problem, but still unable to find what is
wrong.
Provide a correct prototype for malloc():

#include <stdlib.h>
void main( void )
main() always returns an int:

int main( void )
{
char (*string)[20]; ............... ........(1)

string = malloc(10 * sizeof *string); .....(2)
Check the return value of malloc here!
string[0] = NULL; ............... ..........(3)
string[0] is an array to which you cannot assign directly; write:

string[0][0] = '\0';

or (after inclusion of string.h):

strcpy( string[0], "" );

to make string[0] contain an empty string.

main() always returns an int:

return 0; }

Basically, I am allocating memory to an array of strings of 20 chars
max, and setting element 0 of the array to be a NULL value.
Lines (1) to (2) work OK, but line (3) does not work. I wish to set
the string of element 0 to be a NULL value,
As I said above, you cannot assign to an array. Assuming that you want
string[0] to contain an empty string, remember that NULL is a null
pointer constant and neither an empty string nor a null character.
but keeps getting an error
saying:

"left operand must be l-value"


Funny enough, in C99 string[0] /is/ an lvalue, yet not a modifiable one,
thus you still cannot assign to it.

HTH
Regards.
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #6
Bruno Desthuilliers wrote:

sorry, code needed a bit correction before posting...

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
char (*strings)[20];
int i;
int j;
size_t size = 10 * sizeof *strings;

strings = malloc(size); if (strings != NULL) { memset(strings, 0, size);

for (i = 0; i < 10; i++) {
printf("strings[%d] : \n", i);
for (j = 0; j < 20; j++) {
printf(" '%c' ", strings[i][j] + '0');
}
printf("\n");
}

free(strings); }
else {
printf("malloc( ) failed \n");
} return 0;
}


Bruno

Nov 13 '05 #7
Bruno Desthuilliers <bd***********@ removeme.free.f r> wrote:
mike79 wrote:
char (*string)[20]; ............... ........(1)
Not an expert, but I'm not sure the above is correct (any guru out there
?).


Not an expert too, but if OP wants to declare a pointer to array of
20 chars: yes, it's correct.
But well, let's pretend it is and it really means what you want...
string = malloc(10 * sizeof *string); .....(2)
string[0] = NULL; ............... ..........(3)
}
<gurus, please correct me if I'm wrong>

This last line is basically the same as writing :
int main(void)
{
char str20[20];
str20 = NULL;
return 0;
}


Not a guru, but it is similar in that in both cases an attempt is made
to assign to something that is not an (modifiable) lvalue.
This gives me (gcc 3.x, with -Wall -ansi -pedantic switches) :
'incompatible types in assignment'

This does not surprise me, since, while sharing some mechanisms, an
automatic array and a pointer to a dynamically allocated memory block
are two different things.

You can consider str20 as a pointer to the first element of a 20 chars
array (and yes it is, technically), but it's a 'read-only' pointer, in
the meaning that you *can not* modify the *address* it points to.
Yup.
If what you want is to init each element in the 'string' array to the
empty string, you may want to have a look at calloc() or memset() :
Note: the code below not only sets the strings to empty strings,
it 'zeroes' out the whole array.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
char (*strings)[20];
int i;
int j;
size_t size = 10 * sizeof *strings;

strings = malloc(size);
Better check the return value of malloc here.
(OK, I noticed you have already corrected this in a followup post)
memset(strings, 0, size);

for (i = 0; i < 10; i++) {
printf("strings[%d] : \n", i);
for (j = 0; j < 20; j++) {
printf(" '%c' ", strings[i][j] + '0');
This produces misleading output. Better write:

printf(" %d", strings[i][j] );
}
printf("\n");
}

free(strings);
return 0;
}
Note that it *may* not be necessary (at least it *seems* not to be on
Linux with gcc 3.2.2 : commenting out the 'memset()' call doesn't seems
to change the output), but as this could be an UB, I would not rely on
this without the enlightening advices of some guru here (any guru around ?-)


Still not a guru, but malloc just happens to have allocated some memory
that was filled with zeros coincidentally. Relying on this is calling
for nasal demons (aka undefined behaviour).

HTH
Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #8
Hi mike79.

I am french so my English isn't good. First, I don't understand what
this code means. Can you tell me what is your workstation. I am using
Linux and gcc.
Your code doesn't compile on my box. The error is "incompatib le types
assignment in (3)". Tell me what you want to do, maybe I can help you
Hi all,

I have a the following simple piece of code which has taken me hours
to try and sort out the problem, but still unable to find what is
wrong.

void main( void )
{
char (*string)[20]; ............... ........(1)

string = malloc(10 * sizeof *string); .....(2)
string[0] = NULL; ............... ..........(3)
}

Basically, I am allocating memory to an array of strings of 20 chars
max, and setting element 0 of the array to be a NULL value.
Lines (1) to (2) work OK, but line (3) does not work. I wish to set
the string of element 0 to be a NULL value, but keeps getting an error
saying:

"left operand must be l-value"

Please help me, I dont understand what's wrong.

Thank you all in advance,
mike79

Nov 13 '05 #9
Irrwahn Grausewitz wrote:
Bruno Desthuilliers <bd***********@ removeme.free.f r> wrote:

Note: the code below not only sets the strings to empty strings,
it 'zeroes' out the whole array.


Yeps. But the result is technically the same, or IMHO even better since
you're sure to not have garbage trailing in the strings (my 2 cents...).

Or am I wrong ?

(snip code)

Note that it *may* not be necessary (at least it *seems* not to be on
Linux with gcc 3.2.2 : commenting out the 'memset()' call doesn't seems
to change the output), but as this could be an UB, I would not rely on
this without the enlightening advices of some guru here (any guru around ?-)

Still not a guru, but malloc just happens to have allocated some memory
that was filled with zeros coincidentally. Relying on this is calling
for nasal demons (aka undefined behaviour).


Yeps, I guessed it may not be defined behavior (hence my advice not to
rely on this).

Bruno

Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
1807
by: D Witherspoon | last post by:
What is the accepted method of creating a data class or business rules object class with properties that will allow the returning of null values? For example... I have a class named CResults with the following properties. TestID int QuestionID int AnswerID int So, this is a simple example, but I want to be able to know if AnswerID is
1
1405
by: anon | last post by:
I am using Visual Basic.NET 2002 and ADO.NET and am a newbie after using VB4/5/6 for ages. I am used to vb6 where we had the isnull() function to check if something was null so that something could be done about it. Example: text1.text=iif(not isnull(rs.fields(0)) , rs.fields(0), 0) Hence: Text1 is given the value of rs.fields(0) if it is not null, otherwise it
51
3224
by: BigMan | last post by:
Does the C++ standard define what should happen in case of NULL pointer dereferencing. If not, does it say that it is illegal? Where, if so, does it say it?
7
28582
by: Ivan Demkovitch | last post by:
Hi! Here is what I'm doing: I have Login.aspx with code to do forms authentification and I have this line at the end: Response.Redirect(Request.UrlReferrer.ToString()); I have other (non-ASP.NET) pages that post to Login.aspx. THis way I accomplish asp.net authentification.
5
7322
by: Miguel | last post by:
ey, I m trying to make a new httpmodule but the session object is null. I m implementing IReadOnlySessionState but it keep on being null. I m novice in this enviroment, does anybody know what's happening? thanks Miguel
31
17726
by: leonm54 | last post by:
I remember that this is a bad practice, but can not find a definitive resource that states it is bad and why. Can anyone help?
8
3694
by: DaFrizzler | last post by:
Hi, I have received the following email from a colleague, and am quite frankly baffled by the idea. I am just wondering if anyone has any advice or suggestions about this???? === BEGIN MAIL === The DB2 DBA has requested that all columns in the tables be defined as not null with default to improve storage, performance, and ease of
8
2311
by: A. Anderson | last post by:
Howdy everyone, I'm experiencing a problem with a program that I'm developing. Take a look at this stack report from GDB - #0 0xb7d782a3 in strlen () from /lib/tls/i686/cmov/libc.so.6 #1 0xb7d4c2f7 in vfprintf () from /lib/tls/i686/cmov/libc.so.6 #2 0xb7d6441b in vsprintf () from /lib/tls/i686/cmov/libc.so.6 #3 0x08049ba0 in character_data::printf (this=0x800, argument=0x0) at character.c:198
20
3244
by: prashant.khade1623 | last post by:
I am not getting the exact idea. Can you please explain me with an example. Thanks
0
1397
by: dustonheaven | last post by:
I need to calculate running balance on data containing Null, which is sorted by few columns. As example below, Clr is sorted by Null Desc, then by date, then just by ID. So far, I just come out with this... SELECT tr1.Clr, tr1.ID, tr1.Date, tr1.Acc, tr1.Dbt, tr1.Cdt, (SELECT SUM(Nz(tr2.Dbt) - Nz(tr2.Cdt)) FROM tbl00 AS tr2 WHERE (tr2.Acc = tr1.Acc AND tr2.Clr <= tr1.Clr)) AS Bal FROM tbl00 AS tr1 WHERE (((tr1.Acc)=12345) AND...
0
10039
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
11069
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10543
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
8102
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7259
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5944
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4779
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4346
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3370
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.