473,756 Members | 5,660 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Assigning values to char arrays

Hi all,

here's an elementary question. Assume I have declared two variables,

char *a, **b;

I can then give a value to a like

a="hello world";

The question is, how should I assign values to b? A simple

b[0]="string";

results in a segmentation fault.

Answers greatly appreciated.

Regards, Emyl.

Nov 2 '07 #1
43 17226
emyl <kw****@yahoo.c omwrites:
Hi all,

here's an elementary question. Assume I have declared two variables,

char *a, **b;
b is a pointer to a char pointer.
>
I can then give a value to a like

a="hello world";

The question is, how should I assign values to b? A simple

b[0]="string";
*b = "s";
>
results in a segmentation fault.

Answers greatly appreciated.

Regards, Emyl.
Nov 2 '07 #2
emyl said:
Hi all,

here's an elementary question. Assume I have declared two variables,

char *a, **b;

I can then give a value to a like

a="hello world";

The question is, how should I assign values to b? A simple

b[0]="string";

results in a segmentation fault.

Answers greatly appreciated.
Your definition:

char *a, **b;

reserves sufficient storage for a pointer-to-char named a, and a
pointer-to-pointer-to-char named b.

a="hello world";

assigns a value to this pointer-to-char, the value in question being the
address of the first character in the given string literal.

But b[0]="string"; is a problem, not because there's anything wrong with
the syntax, but because you've made an incorrect assumption.

b is a pointer-to-pointer-to-char, but you haven't pointed it to any
pointers-to-char, so it is currently indeterminate. b[0]="string"; is
*not* an attempt to give a value to b. It is an attempt to give a value to
b[0]. But b[0] is meaningless unless b has a meaningful value.

You can give b a meaningful value in any of several ways, but the most
obvious is to allocate some fresh memory for it:

#include <stdlib.h>

/* allocate memory for some pointers-to-char */
char **cpalloc(size_ t n)
{
char **ptr = malloc(n * sizeof *ptr);
if(ptr != NULL)
{
while(n--)
{
ptr[n] = NULL;
}
}
return ptr;
}

#include <stdio.h>

int main(void)
{
char *a, **b;
a = "what has it got in its pocketses?";
b = cpalloc(2);
if(b != NULL)
{
b[0] = "string";
b[1] = "nothing";

printf("%s\n", a);
printf("%s or %s\n", b[0], b[1]);

free(b);
}
return 0;
}

Be careful. The cpalloc function written above does not allocate storage
for strings, only for a collection of pointers to char. A pointer to char
is sufficient for pointing at a string, but not for storing it.

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Nov 2 '07 #3
emyl wrote:
>
here's an elementary question. Assume I have declared two variables,
char *a, **b;
I can then give a value to a like
a="hello world";
The question is, how should I assign values to b? A simple
b[0]="string";
results in a segmentation fault.
"char **b;" declares a pointer to a pointer to char. You could
initialize it with "b = &a;" (provided the a declaration is
present). Then **b is a[0].

However note that your initialization of <a = "hello world";>
leaves a pointing to an unmodifiable string.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Nov 2 '07 #4
Richard <rg****@gmail.c omwrites:
emyl <kw****@yahoo.c omwrites:
>Hi all,

here's an elementary question. Assume I have declared two variables,

char *a, **b;

b is a pointer to a char pointer.
>>
I can then give a value to a like

a="hello world";

The question is, how should I assign values to b? A simple

b[0]="string";

*b = "s";
*slaps cold water on face*

Sorry. That was bullshit. I thought I had included the initialisation
line. See other replies.

Scary.
>>
results in a segmentation fault.

Answers greatly appreciated.

Regards, Emyl.
Nov 2 '07 #5
BIG sigh of relief... Thanks all for your replies. More
specifically,

Richard: Your suggestion is one of the bazillion things I had tried
more or less a
t random. Like you noticed, it won't work. Thanks for taking the
time to answer.

Richard H.: My heartfelt thanks for a crystal clear answer that works
like a charm a
nd is general enough to use it in the broader context of my project.
If I could I'd buy
a beer to you and candy to your kids........... ...

Chuck F.: Thanks a lot for your answer. Of all the simple
possibilities it was the
only one I didn't try, and I guess the only correct one. If I had
thought of that
I'd have had enough of a clue to solve the problem.

Nov 2 '07 #6
On Nov 2, 5:32 am, Richard Heathfield <r...@see.sig.i nvalidwrote:
emyl said:


Hi all,
here's an elementary question. Assume I have declared two variables,
char *a, **b;
I can then give a value to a like
a="hello world";
The question is, how should I assign values to b? A simple
b[0]="string";
results in a segmentation fault.
Answers greatly appreciated.

Your definition:

char *a, **b;

reserves sufficient storage for a pointer-to-char named a, and a
pointer-to-pointer-to-char named b.

a="hello world";

assigns a value to this pointer-to-char, the value in question being the
address of the first character in the given string literal.

But b[0]="string"; is a problem, not because there's anything wrong with
the syntax, but because you've made an incorrect assumption.

b is a pointer-to-pointer-to-char, but you haven't pointed it to any
pointers-to-char, so it is currently indeterminate. b[0]="string"; is
*not* an attempt to give a value to b. It is an attempt to give a value to
b[0]. But b[0] is meaningless unless b has a meaningful value.

You can give b a meaningful value in any of several ways, but the most
obvious is to allocate some fresh memory for it:

#include <stdlib.h>

/* allocate memory for some pointers-to-char */
char **cpalloc(size_ t n)
{
char **ptr = malloc(n * sizeof *ptr);
if(ptr != NULL)
{
while(n--)
{
ptr[n] = NULL;
}
}
I have one question . Can memset be used as
memset(ptr,0,n) ;
Instead of the while loop ?
return ptr;
Nov 2 '07 #7
somenath said:
On Nov 2, 5:32 am, Richard Heathfield <r...@see.sig.i nvalidwrote:
<snip>
> char **ptr = malloc(n * sizeof *ptr);
> if(ptr != NULL)
{
while(n--)
{
ptr[n] = NULL;
}
}
I have one question . Can memset be used as
memset(ptr,0,n) ;
Instead of the while loop ?
Not unless you can guarantee that the representation of null pointers on
all target platforms is all-bits-zero. I don't recall that the OP
mentioned any platforms. The code I supplied was portable to any hosted
implementation.

In situations where you /can/ use memset, don't bother - just calloc it
instead.

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Nov 2 '07 #8
On Nov 2, 11:07 am, Richard Heathfield <r...@see.sig.i nvalidwrote:
somenath said:
On Nov 2, 5:32 am, Richard Heathfield <r...@see.sig.i nvalidwrote:

<snip>
char **ptr = malloc(n * sizeof *ptr);
if(ptr != NULL)
{
while(n--)
{
ptr[n] = NULL;
}
}
I have one question . Can memset be used as
memset(ptr,0,n) ;
Instead of the while loop ?

Not unless you can guarantee that the representation of null pointers on
all target platforms is all-bits-zero. I don't recall that the OP
mentioned any platforms. The code I supplied was portable to any hosted
implementation.

In situations where you /can/ use memset, don't bother - just calloc it
instead.
Many thanks for the response.

But my understanding was in pointer context 0 and NULL is converted to
null pointer. And converting to null pointer is compiler
responsibility. So I thought 0 in memset will be converted to null
pointer (which is system specific).

I would request you to correct me as I am feeling I may be
misunderstood some concept.
Nov 2 '07 #9
Ark Khasin wrote:
Richard wrote:
<snip>
I am not to argue who of us two is more of a newbie, but your post
sheds no light on the question asked. Ego bubbling?
This is most hilarious sentence I've read in c.l.c. this year.

Nov 3 '07 #10

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

Similar topics

1
2128
by: Ched | last post by:
Hi, I am performing a MySQL SELECT (which returns multiple rows) to $result and then extracting the results with mysql_fetch_array($result). I then want to build a number of arrays using the fields of each row. Here is the relevant code: <snip> $result = $i = 1;
2
3390
by: Zitan Broth | last post by:
Greetings All, Running pg 7.3.4 and was reading: http://archives.postgresql.org/pgsql-interfaces/2003-09/msg00018.php . Basically want to assign values to an array and then a 2d array. However I can't get this to run in properly I get a syntax error (at or near ", output_txt_arr TEXT, output_str text ); CREATE OR REPLACE FUNCTION F_TEST(TEXT) RETURNS NUMERIC AS '
14
74893
by: Eric Bantock | last post by:
Very basic question I'm afraid. Once an array has been declared, is there a less tedious way of assigning values to its members than the following: myarray=8; myarray=3; myarray=4; myarray=0; myarray=0; myarray=1; myarray=8;
8
8019
by: chacha | last post by:
char cSubject; chat *h_ptr; If I want to copy the char array pointed by h_ptr to cSubject character by character, does the code looke like the following: strcpy(cSubject+i,*(h_ptr)+i);
2
4697
by: shan_rish | last post by:
Hi CLCers, In the below program the error message while compiling is /home1/murugan/prog/cprog >cc -o struct_eval struct_eval.c cc: "struct_eval.c", line 14: error 1549: Modifiable lvalue required for assignment operator. cc: "struct_eval.c", line 17: error 1549: Modifiable lvalue required for assignment operator. cc: "struct_eval.c", line 18: error 1549: Modifiable lvalue required for assignment operator.
2
7053
by: assgar | last post by:
Hi Developemnt on win2003 server. Final server will be linux Apache,Mysql and PHP is being used. I use 2 scripts(form and process). The form displays multiple dynamic rows with chechboxs, input box for units of service, description of the service and each row has its own dropdown list of unit fees that apply. Each dynamically created row will return 3 values fee1_choice, fee1_unit and fee1_money. Note The above informaton is...
3
3494
by: ZMan | last post by:
The following code won't compile with gcc version 3.4.2 (mingw-special). How come? Error: cannot convert `char (*)' to `char**' /**********************************************************/ #include <cstdio> #define MAX_WORD_LEN 80 #define MAX_SIZE 1000
17
18768
by: Cliff | last post by:
Hi, I'm in the process of porting some code from a 3rd party and have hit a problem with the following: typedef struct { unsigned char Red; unsigned char Green; unsigned char Blue; }TBoxColour;
11
2058
by: rep_movsd | last post by:
Hi I program primarily in C++ , but once in a while one is forced to use the odd strcpy or call API functions that dump results into char* buffers. I believe that most security exploits that work by thrashing the stack to overwrite the return address, allowing arbitrary code execution. I have now fallen into the habit of declaring temporary buffers as static char arrays.
7
4512
by: daniel | last post by:
Hello , I always had the feeling that is better to have char arrays with the size equal to a power of two. For example: char a_str; // feels ok char b_str; //feels not ok.
0
9297
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10069
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
9904
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8736
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7285
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
6556
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
5168
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
3828
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
3395
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.