473,796 Members | 2,654 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
16 2408
mi****@iprimus. com.au (mike79) wrote in message news:<49******* *************** ***@posting.goo gle.com>...
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.
I think you're confused (or I'm confused!)
void main( void )
int main (void)

main() returns an int. Always.
{
char (*string)[20]; ............... ........(1)
this doesn't mean what you think it means (I think).

string is a ptr-to-array-of-char

it's pretty unusual to use ptrs-to-array (they give me a headache).

did you mean
char *string [20];

ie. array-of-ptr-to-char

or what people normally call an array of strings
string = malloc(10 * sizeof *string); .....(2)
well if you meant ptr-to-array
string = malloc (sizeof *string);

and if you meant array-of-ptr (array of strings)
string [0] = malloc (10 * sizeof *(string [0]);
string[0] = NULL; ............... ..........(3)
if you meant a single pointer to an array
(*string) = '\0'; /* don't use NULL here */

if you meant an array of strings
string [0] = NULL; /* first string is empty */

or
string [0][0] = '\0'; /* first string is zero length */

I'm bound to have got one of these wrong...
}

Basically, I am allocating memory to an array of strings of 20 chars
max,
that sounds like an array-of-ptr-to-char but this doesn't limit the
string length.
and setting element 0 of the array to be a NULL value.
element 0 of the array or element 0 of the first string?
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.


If you still don't understand (or I mis-explained) K&R is pretty good
on pointers and C declarations.
--
Nick Keighley

It's probably not the quickest method around,
but it uses plenty of trees, and that's what counts.
Richard Heathfield
Nov 13 '05 #11
Bruno Desthuilliers <bd***********@ removeme.free.f r> wrote:
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,


Right, I just found it worth mentioning, for the sake of completeness.
or IMHO even better since
you're sure to not have garbage trailing in the strings (my 2 cents...).
An array filled with zeros is a "even more empty" string? ;-))
Or am I wrong ?
Nope.
(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).


And you were dead on.
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #12
In <49************ *************@p osting.google.c om> mi****@iprimus. com.au (mike79) writes:
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 ) ^^^^
You should have read the FAQ *before* posting!
{
char (*string)[20]; ............... ........(1)
What do you think string (as declared above) is?
string = malloc(10 * sizeof *string); .....(2)
string[0] = NULL; ............... ..........(3)
What do you get by dereferencing string? Is it a modifiable lvalue?
}

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.


Do NOT declare and use pointers to arrays until you understand what they
really are and how they really work.

string[0] is an array of 20 char's, you can't assign anything to it.

Try to use an array of pointers instead. It's a much easier to grasp
concept, in C.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #13
mi****@iprimus. com.au (mike79) wrote in message news:<49******* *************** ***@posting.goo gle.com>...
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 ) ^^^^^^^^^^^^^

What is the above void doing here. Don't you think your program must
returing some thank you note to the OS for doing it's job.
{
char (*string)[20]; ............... ........(1)

string = malloc(10 * sizeof *string); .....(2) ^^^^^^

Again you are not expressive enough. Albeit here for the compiler, you
are not telling it to include <stdblib.h> which has the prototype for
the malloc.
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.


The problem is again in expression you are not expressing what you
want when you write

char (*str) [20];

You are declaring a single pointer not an array of pointers, here str
is pointer to an "array" of 20 characters.

so (*str) is effectively is an array of 20 characters. You can't
modify an array which is a l-value.
ITYM

char (*str)[20];

HTH

--
Imanpreet Singh Arora

isingh AT acm DOT org
Nov 13 '05 #14
mi****@iprimus. com.au (mike79) wrote in message news:<49******* *************** ***@posting.goo gle.com>...
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 )
int main (void) /* main always returns int */
{
char (*string)[20]; ............... ........(1)
This doesn't do what you think it does. You are declaring a pointer
to a single 20-element array of char.

Here's a handy chart that may help:

char h; /* h is a single char */
char *h; /* h is a pointer to char */
char **h; /* h is a pointer to a pointer to char */
char h[N]; /* h is an N-element array of char */
char *h[N]; /* h is an N-element array of pointers to
char */
char **h[N]; /* h is an N-element array of pointers to
pointers to char */
char (*h)[N]; /* h is a pointer to an N-element array of
char */
char h[M][N]; /* h is an M-element array of N-element
arrays of char */
char *h[M][N]; /* h is an M-element array of N-element
arrays of pointers to char */
char (*h)[M][N]; /* h is a pointer to an M-element array
of N-element arrays of char */
char *(*h)[M][N]; /* h is a pointer to an M-element array
of N-element arrays of pointers to char
*/
char (*h[M])[N]; /* h is an M-element array of pointers
to N-element arrays of char */
char *(*h[M])[N]; /* h is an M-element array of pointers
to N-element arrays of pointer to char
*/
char (**h)[N]; /* h is a pointer to a pointer to an
N-element array of char */

....and then it starts getting ugly, but I think you can work out the
pattern from there.

To do what you want to do, you don't want to mess with pointers to
arrays. Trust me. There's a reason they aren't used much.

Here's a method that's 70% less headache-inducing:

#include <stdlib.h>

#define STRSIZE 20
#define ARRSIZE 10

int main (void)
{
char **p; /* p will become an array of pointers to char */

int i;

/*
** allocate a block of memory big enough to hold 10 pointers to
char,
** assign the address to p.
*/
p = malloc (ARRSIZE * sizeof *p)

if (p)
{
/*
** allocate the individual 20-element arrays of char, assign
each
** address to p[i]
*/
p[0] = NULL; /* make the first array element NULL */
for (i = 1; i < ARRSIZE; i++)
{
p[i] = malloc (sizeof **p * STRSIZE);
}
}

return 0;
}

Of course, this doesn't guarantee that all the memory is contiguous.
If that's a requirement, you'll have to do something else. Personally
I'd allocate a single huge block of ARRSIZE * STRSIZE characters, and
set up a separate array of pointers into it:

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

#define STRSIZE 20
#define ARRSIZE 10

int main (void)
{
char *p; /* single big array of bytes */
char *h[ARRSIZE]; /* array of pointers into p */

p = malloc (STRSIZE * ARRSIZE * sizeof *p);
if (p)
{
int i;
h[0] = NULL;
for (i = 1; i < arrsize; i++)
{
/*
** get the address of each 20-element substring in p,
assign
** to h[i]; h[1] = &p[20], h[2] = &p[40], etc.
*/
h[i] = &p[i*STRSIZE];
}
}

return 0;
}

It looks ugly, but it's still less of a pain in the ass than dealing
with pointers to arrays.

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"
This is going to be a bit twisted, and I'll probably botch it, but
here goes.

Remember that you have declared string as a pointer to a 20-element
array of char. Remember that the subscript expression a[i] is
evaluated as *(a + i); the type of that expression is the base type of
a. IOW, string[0] is evaluated as *(string + 0), or just *string, and
the type of *string is 20-element array of char.

An object of array type may not appear on the left-hand side of an
assignment expression, which is why you got the error above. It's the
equivalent of writing

int a[10];
a = NULL;

Such an operation is not allowed in C. Array objects cannot be
assigned to.

Yet another reason why you don't want to use pointers to arrays. In
almost 15 years of writing code professionally I've never had occasion
to use them. I'm sure they're useful in some obscure context, but I
haven't found it yet.

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

Thank you all in advance,
mike79

Nov 13 '05 #15


John Bode wrote:

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

#define STRSIZE 20
#define ARRSIZE 10

int main (void)
{
char *p; /* single big array of bytes */
char *h[ARRSIZE]; /* array of pointers into p */

p = malloc (STRSIZE * ARRSIZE * sizeof *p);
if (p)
{
int i;
h[0] = NULL; Why are you assigning h[0] NULL?
This would be a disaster if you then do something like:
strcpy(h[0],"Hello World");
for (i = 1; i < arrsize; i++)
{
/*
** get the address of each 20-element substring in p,
assign
** to h[i]; h[1] = &p[20], h[2] = &p[40], etc.
*/
h[i] = &p[i*STRSIZE];
}
}

return 0;
}


I think what you are getting at is this:

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

#define STRSIZE 20
#define ARRSIZE 10

int main (void)
{
char **p;
int i;

if((p = malloc(ARRSIZE* (sizeof *p))) == NULL) return EXIT_FAILURE;
if((*p = malloc(ARRSIZE * STRSIZE *(sizeof **p))) == NULL)
{
free(p);
return EXIT_FAILURE;
}
for(i = 1; i < ARRSIZE;i++) p[i] = *p+(i*STRSIZE);
strcpy(p[0], "Abe Lincoln");
strcpy(p[1], "George Washington");
strcpy(p[2], "George Bush");
/* On and on to assign the full array of 10 char *'s */
puts(p[0]);
puts(p[1]);
puts(p[2]);
/* And to free */
free(*p);
free(p);
return EXIT_SUCCESS;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 13 '05 #16
Irrwahn Grausewitz wrote:
Bruno Desthuilliers <bd***********@ removeme.free.f r> wrote:
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,


Right, I just found it worth mentioning, for the sake of completeness.


Right.
or IMHO even better since
you're sure to not have garbage trailing in the strings (my 2 cents...).

An array filled with zeros is a "even more empty" string? ;-))


Lol !-)

Bruno

Nov 13 '05 #17

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

Similar topics

12
1800
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
1400
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
3193
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
28570
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
7312
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
17711
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
3690
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
2302
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
3235
by: prashant.khade1623 | last post by:
I am not getting the exact idea. Can you please explain me with an example. Thanks
0
1395
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
9679
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...
0
10453
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10003
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
7546
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
6785
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
5441
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
4115
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
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2924
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.