473,783 Members | 2,516 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

passing pointer to function - modify in different function not working

Hi all,
What I am trying to do is to pass a pointer to the first element of
an array to a function, modify it in that function, and then print out
the values of the array (which has been modified by the function) in
main. However, I am getting a segmentation fault. Here is the code:
(Please note, the size is fixed in this code, but in my code where I am
actually going to use this, the size of the array is not known until
you get to the modify function which is why I am using pointer
notation).

#include <stdio.h>

void modifiy( int* nums );

int main() {
int* nums;
int i;

for (i=0; i < 5; i++) {
printf("%d", nums[i]);
}

}

void modify( int* nums ) {
int i;
nums = (int*)malloc( 5*sizeof(int));
for (i=0; i < 5; i++) {
nums[i] = i;
}
}

Once I can get this to work, I want to do the same thing w/ double
arrays, so if there are any pitfalls associated with that, any help
would be greatly appreciated.

thanks!

Jan 18 '07 #1
6 7875
"Kiran" <Ki*********@gm ail.comwrites:
int main() {
int* nums;
int i;

for (i=0; i < 5; i++) {
printf("%d", nums[i]);
}
You should return a value from main(), probably 0.
}

void modify( int* nums ) {
int i;
nums = (int*)malloc( 5*sizeof(int));
I don't recommend casting the return value of malloc():

* The cast is not required in ANSI C.

* Casting its return value can mask a failure to #include
<stdlib.h>, which leads to undefined behavior.

* If you cast to the wrong type by accident, odd failures can
result.

In unusual circumstances it may make sense to cast the return value of
malloc(). P. J. Plauger, for example, has good reasons to want his
code to compile as both C and C++, and C++ requires the cast, as he
explained in article <9s************ *****@nwrddc01. gnilink.net>.
However, Plauger's case is rare indeed. Most programmers should write
their code as either C or C++, not in the intersection of the two.

When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type. For instance,
*don't* write this:

int *x = malloc (128 * sizeof (int)); /* Don't do this! */

Instead, write it this way:

int *x = malloc (128 * sizeof *x);

There's a few reasons to do it this way:

* If you ever change the type that `x' points to, it's not
necessary to change the malloc() call as well.

This is more of a problem in a large program, but it's still
convenient in a small one.

* Taking the size of an object makes writing the statement
less error-prone. You can verify that the sizeof syntax is
correct without having to look at the declaration.

for (i=0; i < 5; i++) {
nums[i] = i;
}
}
Your real problem is in the FAQ:

4.8: I have a function which accepts, and is supposed to initialize,
a pointer:

void f(int *ip)
{
static int dummy = 5;
ip = &dummy;
}

But when I call it like this:

int *ip;
f(ip);

the pointer in the caller remains unchanged.

A: Are you sure the function initialized what you thought it did?
Remember that arguments in C are passed by value. The called
function altered only the passed copy of the pointer. You'll
either want to pass the address of the pointer (the function
will end up accepting a pointer-to-a-pointer), or have the
function return the pointer.

See also questions 4.9 and 4.11.

--
"Large amounts of money tend to quench any scruples I might be having."
-- Stephan Wilms
Jan 18 '07 #2
Ben Pfaff writes:
Your real problem is in the FAQ:
He'd also be a step closer if main() actually called modify() :-)

--
Hallvard
Jan 18 '07 #3
Hi all,
first of all thanks for your responses.
yes, i forgot to put that in (and also the function prototype is
misspelled), but the result is the same, and after reading the faq, i
think i understand why its going wrong, but not how to fix it.

This is my understanding.
The pointer itself is a variable, in this case containing the address
of the first element in the array called nums, so when i pass modify
nums, the function modify gets its own copy of where nums in main
points to? (but if thats the case, shouldnt they both still point to
the same thing?) I think I am confusing myself here.

anyway, thanks again for all of yoru help.

Hallvard B Furuseth wrote:
Ben Pfaff writes:
Your real problem is in the FAQ:

He'd also be a step closer if main() actually called modify() :-)

--
Hallvard
Jan 18 '07 #4
Kiran writes:
This is my understanding.
The pointer itself is a variable, in this case containing the address
of the first element in the array called nums, so when i pass modify
nums, the function modify gets its own copy of where nums in main
points to? (but if thats the case, shouldnt they both still point to
the same thing?) I think I am confusing myself here.
If you allocate the memory in main(), yes. Or if you just declare
int nums[5];
or whatever in main().

If you allocate 'nums' in modify(), then when you modify the pointer
in that function, the change doesn't affect 'nums' in main(). Unless
you return 'nums' from modify() and do 'nums = modify()' in main,
or if you do
void modify(int **nums_ptr);
and call it as
main(&nums);

--
Hallvard
Jan 18 '07 #5
Kiran wrote:
Hi all,
first of all thanks for your responses.
Please don't top-post. Your replies belong following or interspersed
with properly trimmed quotes. See the majority of other posts in the
newsgroup, or:
<http://www.caliburn.nl/topposting.html >
Jan 18 '07 #6
Ben Pfaff <bl*@cs.stanfor d.eduwrote:
I don't recommend casting the return value of malloc():
Neither does the FAQ: http://c-faq.com/malloc/cast.html (Not to say
that your explanation wasn't excellent, just possibly unnecessary.)

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gma il.com | don't, I need to know. Flames welcome.
Jan 18 '07 #7

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

Similar topics

58
10181
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
1
2120
by: george doubleu | last post by:
hi, i'm using "gcc version 3.3.3 (Debian)" to compile the program pasted below. I get the two warnings you can see in the remarks. The second warning is perfectly OK for me, but the first one I don't understand. Isn't the "const int *" construct in the signature of func1 a hint for the user, that func1 doesn't modify **arg? Why then is it dangerous to pass an alterable argmument?
18
1616
by: hzmonte | last post by:
typedef int t_compare_func(const void *, const void *); struct node *tree_search(struct node *root, const void *keyy, t_compare_func *comp) { struct node *cur_item; int result; if (root == NULL) return NULL; cur_item = root; while (cur_item != NULL) {
11
8131
by: John Pass | last post by:
Hi, In the attached example, I do understand that the references are not changed if an array is passed by Val. What I do not understand is the result of line 99 (If one can find this by line number) which is the last line of the following sub routine: ' procedure modifies elements of array and assigns ' new reference (note ByVal) Sub FirstDouble(ByVal array As Integer()) Dim i As Integer
1
3269
by: Shawn | last post by:
As if it won't be clear enough from my code, I'm pretty new to C programming. This code is being compiled with an ANSI-C compatible compiler for a microcontroller. That part, I believe, will be irrelavent. My syntax is surely where I am going wrong. I'd like to be able to call this routine to read different values from another device. This routine would be called quite simply as follows: void main() {
12
5403
by: Mike | last post by:
Consider the following code: """ struct person { char *name; int age; }; typedef struct person* StructType;
17
3264
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ================================================================================ /* A function that returns a pointer-of-arrays to the calling function. */ #include <stdio.h> int *pfunc(void);
6
3030
by: Roman Mashak | last post by:
Hello, I belive the reason of problem is simple, but can't figure out. This is piece of code: struct timeval { long tv_sec; /* seconds */ long tv_usec; /* microseconds */ };
7
3307
by: TS | last post by:
I was under the assumption that if you pass an object as a param to a method and inside that method this object is changed, the object will stay changed when returned from the method because the object is a reference type? my code is not proving that. I have a web project i created from a web service that is my object: public class ExcelService : SoapHttpClientProtocol {
0
10313
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
10147
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
8968
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
7494
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
6735
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
5378
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...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3643
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2875
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.