473,387 Members | 3,810 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Changing the size of an array passed to a function problem!

Hi all,

I have the following scenario:

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.    char a[] = "Hello";
  4.    printf("Modified string: %s\n", modify_str(a));
  5. }
  6.  
  7. char *modify_str(char *b)
  8. {
  9.    /* Insert a  '+'  after every letter in the string */
  10.    /* "Hello" becomes "H+e+l+l+o+" */
  11.    return b;
  12. }
  13.  
Now my problem is that the length of the string doubles after the operation is over. So how do I re-size the memory pointed to by 'b' to accommodate the change in size of the string?

I cannot have a local array of twice the size of 'b' and return that because that would be returning a local pointer.

Will this be correct and work fine? -->
Expand|Select|Wrap|Line Numbers
  1. char *modify_str(char *b)
  2. {
  3.    char *local;
  4.    local = (char *)malloc(strlen(b)*2 + 1);
  5.    /* 'local' gets filled up with the modified 'b' */
  6.    b = local;    /* Is this wrong? Why is this wrong?? */
  7.    return b;
  8. }
Please if somebody could help :((
-
-Sid
May 20 '09 #1
6 2157
JosAH
11,448 Expert 8TB
Yes you could that and it'll work fine (don't forget to free that chunk of memory when you don't need it anymore) but if we're talking C++ there's the string class which does it all for you.

kind regards,

Jos
May 20 '09 #2
Banfa
9,065 Expert Mod 8TB
A few points, to start with this

Expand|Select|Wrap|Line Numbers
  1.     b = local;    /* Is this wrong? Why is this wrong?? */
  2.     return b;
  3.  
pointlessly modifies b and can be written as

Expand|Select|Wrap|Line Numbers
  1.     return local;
  2.  
Modifying b does nothing for you and is an operation that has no effect on the operation of main.

You have malloc'd the data for use in the return pointer, that means at some point you will need to free it otherwise you will have a memory leak. That means that the calling code can not just use the return pointer (pass it straight to printf) but has to store it in another variable so that it can free the data pointed to after calling printf.

And finally some people would consider it bad form to write code such that the calling function has to have knowledge of how the called function operates internally in order to correctly use it. A better method to write this function might be for it to have 2 parameters, 1 pointer to the source string and 1 pointer to the place to store the result string. The calling function would have to make sure the result string had enough characters to store the result. Or better yet add a third parameter, the size of the result string and the function caninsure that it does not overwrite the end of it.
May 20 '09 #3
@Banfa
Thanks to you Mr.Banfa I got my code working after incorporating the above suggestions. I'm thankful to you for telling me a more efficient way of doing this.
Thanks to Mr.JoshAH as well.

I guess this question really boils down to the solution for returning a char array from a function. :p
Be back with more queries as I learn.
-Sid
May 20 '09 #4
weaknessforcats
9,208 Expert Mod 8TB
I guess this question really boils down to the solution for returning a char array from a function. :p
You cannot return arrays from a function. You can only return a type or a pointer to a type.

First, read this article: http://bytes.com/topic/c/insights/77...rrays-revealed.

Assuming you have read the article at this point, you can see that you pass the address of element 0 of the array to the function as an argument and the function can then access the array through the pointer.
May 20 '09 #5
There is another method to achieve what you want: pass a char** pointer.
You can do the following:

Expand|Select|Wrap|Line Numbers
  1. void MyFunc(char** ppString)
  2. {
  3.      // notice how we dereference ppString to get the initial pointer
  4.      ralloc( *ppString, strlen(ppString) * 2 + 1);
  5.      *ppString[ strlen(ppString) * 2 ] = 0; // ensure that the string is terminated
  6.  
  7.      // TODO: modify the contents of ppString any way you want
  8.      // you can use *ppString[i] to access individual characters
  9. }
  10.  
  11. char* pStr;
  12. // TODO: init pStr
  13. MyFunc(&pStr); 
The above code will resize pStr and change it's contents in any way you want it. For safety reasons, you should add another integer that will contain the string size. You could also optimize the function further by using fastcall calling conversion, but this is compiler specific.

This is generally, the fastest way to do it and has virtually no memory overhead. On the other hand if performance isn't an issue and can you use a C++ compiler, std::string will make your life much easier.
May 20 '09 #6
@weaknessforcats
weaknessforcats that was a wonderful tut. I was actually referring to the solution given by Banfa, which is nothing but a solution to the problem of not being able to "return" string.
A better method to write this function might be for it to have 2 parameters, 1 pointer to the source string and 1 pointer to the place to store the result string. The calling function would have to make sure the result string had enough characters to store the result. Or better yet add a third parameter, the size of the result string and the function caninsure that it does not overwrite the end of it.
:O)

@unauthorized
Thanks a lot for telling about the alternate way of doing this although I gotta admit double pointers make me a little woozy! :p Deferring implementation until coding God-mode is acquired. :O)

Thanks again,
Sid.
May 22 '09 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: matthurne | last post by:
I need to send just an array to a function which then needs to go through each element in the array. I tried using sizeof(array) / sizeof(array) but since the array is passed into the function,...
11
by: Sontu | last post by:
Consider the following code: int main(void) { char buffer; func(buffer); } void func(char *bufpas) {
18
by: bsder | last post by:
Hi, Can anyone please tell me how to calculate the size of the following 4-dimensional array, and now to use qsort for sorting on this array? double sp = { 4.0, 5.0, 6.0 }; double spa = { {...
4
by: Phillip Ian | last post by:
Version: VS 2005 I took the sample code from help about encrypting and decrypting strings, and changed it to work directly with byte arrays and get the key and IV values from functions I've...
12
by: manochavishal | last post by:
Hi, I have a question. How can i know the size of array when it is passed to a function. For Example i have this code: #include <stdio.h> #include <stdlib.h>
29
by: Vasileios Zografos | last post by:
Hi everyone, I need to build a function to plug it in a program (that I didnt make or can change) that should be called something like this: float someFunction(float x) { ...
7
by: bowlderster | last post by:
Hello,all. I want to get the array size in a function, and the array is an argument of the function. I try the following code. /*************************************** */ #include<stdio.h>...
4
by: gubbachchi | last post by:
Hi all, Please anybody help me solve this problem. I am stuck up with this from past 2 weeks. I am developing an application where, when the user selects date from javascript datepicker and enters...
30
by: Angel Tsankov | last post by:
Hello! Does the C++ standard define what happens when the size argument of void* operator new(size_t size) cannot represent the total number of bytes to be allocated? For example: struct S {...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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
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
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,...

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.