473,503 Members | 6,354 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pointers and Arrays in C??

I usually program in Java, so I am a bit confused about usint pointers in C.
I would really appreciate if someone can help me.

Case 1:
======

// Is this function no good? Since str is a variable created on stack,
// I am assuming it will be deallocated immedately after the function returns,
// right??
char * generateString()
{
char str[100] = "abc";
return str;
}

Case 2:
=====

// str is a pointer pointing to a literal
// Can I use str just like other char arrays?
// How are memory allocated for literals and when are they deallocated??
void main()
{
char * str;
str = "abc";
}

Case 3:
=====

// Similar to case 2 except the literal is returned from a function
// Again, can I use str for anything? When is it deleted from memory??
void main()
{
char * str;
str = generateString();
}

char * generateString()
{
return "abc";
}

Case 4:
=====

// assigning dynamically allocated array to pointer
void main()
{
char * str;
str = generateString();
...
delete str; // I have to delete str at the end, Right?
}

char * generateString()
{
char * charArray = new char[20];
strcpy(charArray, "abc");
return charArray;
}

Case 5:
=====

// str points to a char array created in a C library function
// How was this char array allocated? When will it be deallocated?
// Do I have to delete it explicitly??
void main()
{
char line[20] = "abc#def";
char * str;

str = strtok(line, "#");

delete str; // is this necessary?
// can I modify the content of the array??
}

Nov 13 '05 #1
5 2085
Terence wrote:
I usually program in Java, so I am a bit confused about usint pointers in C.
I would really appreciate if someone can help me.
Answered in news:comp.lang.c++ (your use of `new' makes it OT on c.l.c).

Posting to multiple newsgroups is usually not a good idea -- and
when it is, crosspost, DO NOT multipost.

--ag

Case 1:
======

// Is this function no good? Since str is a variable created on stack,
// I am assuming it will be deallocated immedately after the function returns,
// right??
char * generateString()
{
char str[100] = "abc";
return str;
}

Case 2:
=====

// str is a pointer pointing to a literal
// Can I use str just like other char arrays?
// How are memory allocated for literals and when are they deallocated??
void main()
{
char * str;
str = "abc";
}

Case 3:
=====

// Similar to case 2 except the literal is returned from a function
// Again, can I use str for anything? When is it deleted from memory??
void main()
{
char * str;
str = generateString();
}

char * generateString()
{
return "abc";
}

Case 4:
=====

// assigning dynamically allocated array to pointer
void main()
{
char * str;
str = generateString();
...
delete str; // I have to delete str at the end, Right?
}

char * generateString()
{
char * charArray = new char[20];
strcpy(charArray, "abc");
return charArray;
}

Case 5:
=====

// str points to a char array created in a C library function
// How was this char array allocated? When will it be deallocated?
// Do I have to delete it explicitly??
void main()
{
char line[20] = "abc#def";
char * str;

str = strtok(line, "#");

delete str; // is this necessary?
// can I modify the content of the array??
}


--
Artie Gold -- Austin, Texas
Oh, for the good old days of regular old SPAM.

Nov 13 '05 #2
In article
<mg*******************@twister01.bloor.is.net.cabl e.rogers.com>,
"Terence" <fi****@hotmail.com> wrote:
I usually program in Java, so I am a bit confused about usint pointers in C.
I would really appreciate if someone can help me.


Your last two examples look more like C++ than C, and the main function
must be declared as returning int, not void. Apart from that:

1. Automatic variables disappear when you return from the function
containing them. Any pointer to such an auto variable becomes invalid,
and using it invokes undefined behavior.

2. Static and extern variables live as long as the program is running;
they never disappear. String literals like "abc" behave like static char
arrays; they live as long as the program is running and never disappear.
A pointer to a static or extern variable stays valid forever.

3. Calling free () with an argument that is the address of an auto,
static or extern variable invokes undefined behavior; most likely your
computer will crash rather soon.
Nov 13 '05 #3
Christian Bau <ch***********@cbau.freeserve.co.uk> writes:
[...]
3. Calling free () with an argument that is the address of an auto,
static or extern variable invokes undefined behavior; most likely your
computer will crash rather soon.


Crashing your computer is certainly a possible consequence of
undefined behavior (as is making demons fly out of your nose), but in
a well-designed operating system you're far more likely to crash just
your application. (Discussion of which operating systems are
well-designed is off-topic.)

--
Keith Thompson (The_Other_Keith) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #4
On Thu, 30 Oct 2003 23:36:50 +0000, Terence wrote:
I usually program in Java, so I am a bit confused about usint pointers in C.
I would really appreciate if someone can help me.

Case 1:

// Is this function no good?
char * generateString()
{
char str[100] = "abc";
return str;
}
You are correct, it is no good. The pointer returned will be invalid
because the array 'str' will no longer exist.
Case 2:

// Can I use str just like other char arrays?
// How are memory allocated for literals and when are they deallocated??
void main()
This is not correct. Use:

int main (void)
{
char * str;
str = "abc";
}
This is ok. String literals exist the entire time the program is
running. However, writing to string literals is a no-no.
Case 3:
Same as Case 2
Case 4:

// assigning dynamically allocated array to pointer
void main()
int main (void)
{
char * str;
str = generateString();
...
delete str; // I have to delete str at the end, Right?
There is no such thing as 'delete' in C. You meant to type

free(str);

You do not have to free the memory pointed to by str before your
memory ends if you don't want to make the memory available for
further allocation, but it is a good idea to do it anyway.
}

char * generateString()
{
char * charArray = new char[20];
This is no such thing as 'new' in C. You meant to type

char * charArray = malloc(20);

You must also check to make sure that the call to malloc
succeeded, like this:

if (charArray == NULL)
{
printf("memory allocation failed\n");
exit (EXIT_FAILURE);
}

Note that in order to use the NULL and EXIT_FAILURE macros
you need to #include <stdlib.h> before the use (the top of
the source file is a good place)

Dynamically allocated memory exists from the point of allocation
with malloc() until it is deallocated using free() (or until
your program ends).
strcpy(charArray, "abc");
return charArray;
}

Case 5:
=====

// str points to a char array created in a C library function
// How was this char array allocated? When will it be deallocated?
// Do I have to delete it explicitly??
void main()
#include <string.h> /* this is necessary to use strtok() */
int main (void)
{
char line[20] = "abc#def";
char * str;

str = strtok(line, "#");

delete str; // is this necessary?
You meant to type

free(str);

It is not necessary. In fact, it is very very wrong.
strtok() does not return any newly allocated memory. The pointers
it returns are pointers into your array.
// can I modify the content of the array??
Yes. It is your array line, which is modifiable.
}

-Sheldon

Nov 13 '05 #5
Terence <fi****@hotmail.com> spoke thus:
// Is this function no good? Since str is a variable created on stack,


FWIW, whether str ends up on a stack is implementation-dependent - some
implementations do not maintain stacks. In any case, you are correct about the
behavior of your example.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 13 '05 #6

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

Similar topics

19
6804
by: Thomas Matthews | last post by:
Hi, Given a structure of pointers: struct Example_Struct { unsigned char * ptr_buffer; unsigned int * ptr_numbers; }; And a function that will accept the structure:
11
6701
by: Linny | last post by:
Hi, I need some help in declaring an array of pointers to array of a certain fixed size. I want the pointers to point to arrays of fixed size only (should not work for variable sized arrays of the...
79
3331
by: Me | last post by:
Just a question/observation out of frustration. I read in depth the book by Peter Van Der Linden entitled "Expert C Programming" (Deep C Secrets). In particular the chapters entitled: 4: The...
6
3150
by: Carl-Olof Almbladh | last post by:
Already in the 1st edition of the "White book", Kerigham and Ritchie states the "C is a general purpose language". However, without what is usually called "assumed size arrays" and built-in...
5
3111
by: Paminu | last post by:
Why make an array of pointers to structs, when it is possible to just make an array of structs? I have this struct: struct test { int a; int b;
36
2796
by: raphfrk | last post by:
I have the following code: char buf; printf("%lp\n", buf); printf("%lp\n", &buf); printf("%lp\n", buf); printf("%lp\n", buf); printf("%d\n", buf-buf);
14
2015
by: code break | last post by:
what is the difference in this pointers decalarition ? int *ptr; and int (*ptr);
6
491
by: joelperr | last post by:
Hello, I am attempting to separate a two dimensional array into two one-dimensional arrays through a function. The goal of this is that, from the rest of the program, a data file consisting of...
8
2895
by: Piotrek | last post by:
Hi, Like almost all of beginners I have problem understanding pointers. Please, look at this piece of code, and please explain me why myswap function doesn't work as it's supposed to do, whereas...
0
1282
by: David Thompson | last post by:
On Wed, 09 Apr 2008 12:34:43 +0500, arnuld <arnVuld@ippiVmail.com> wrote: I think you've got the idea, but: - I would be careful about using 'equal'. Pointers and arrays are different things,...
0
7207
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,...
0
7093
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...
0
7357
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...
1
7012
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...
0
5598
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,...
1
5023
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...
0
4690
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...
0
3180
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...
0
3171
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.