473,608 Members | 2,479 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning pointer to array problem II

hi!

the code is cinpiling with gcc -ansi -pedantic. so Iam back to my question
Iam trying to make program were I enter string and serach char.
and funktion prints out witch position char is found this
is done if funktion serach_char. so far all good
what I want do next is:
return, from funktion, pointer value to array were
positions ( of found char) is stored. and print that array from main.
but I only manage to print memory adress to array..

any suggestions?

#include <stdio.h>
int search_char( char *pStr , char *pSearch );

int main(void){
char cStr[201];
char cSearch[21];
int *pInt;
int i ;
printf("Enter string\n");
scanf("%s", cStr);
printf("Enter search char\n");
scanf("%s", cSearch); /*reading it as string becouse I want to
by able later search 2 chars and more*/
*pInt = search_char( &cStr , &cSearch );
for(i=0;i<20;i+ +){
printf("%d\n",& pInt[0]);
}
return 0;
}

int search_char( char *pStr , char *pSearch ) {
int i;
int vPossition[201];
for( i=0;i<=200;i++) {
if(pStr[i] == pSearch[0]){
printf("Found %c in position %d \n", pStr[i],i+1);
vPossition[i] = i;/*position into array*/
}
}
return vPossition;
}

--

Thanx in advance
_______________ _________
BTW. I know my english is not best in the word, so please stop bugging me
about my speling. And yes Iam sorry you don't understand what I mean, but
there is no point to yell at me. Have a nice day.

Nov 14 '05 #1
3 1843
Carramba <no****@note.co m> wrote:
the code is cinpiling with gcc -ansi -pedantic.
You better also use '-W' and '-Wall'...
so Iam back to my question
Iam trying to make program were I enter string and serach char.
and funktion prints out witch position char is found this
is done if funktion serach_char. so far all good
what I want do next is:
return, from funktion, pointer value to array were
positions ( of found char) is stored. and print that array from main.
but I only manage to print memory adress to array.. any suggestions? #include <stdio.h>
int search_char( char *pStr , char *pSearch ); int main(void){
char cStr[201];
char cSearch[21];
int *pInt;
int i ;
printf("Enter string\n");
scanf("%s", cStr);
printf("Enter search char\n");
scanf("%s", cSearch); /*reading it as string becouse I want to
by able later search 2 chars and more*/
I hope you understand that this use of scanf() is dangerous - if the
user inputs more non-white-space characters than the char arrays
are long then your program writes past the end of these arrays...
*pInt = search_char( &cStr , &cSearch );
If search_char() would return an int pointer (as it probably should) then
this would have to be written as

pInt = search_char( cStr, cSearch );

Note that all the '*'s and '&'s you are using don't make sense. On
the keft hand side you have a pointer and you want to assign the
return value to that pointer, not to what it's pointing to. On the
right hand side both arrays are already passed by pointer to the
first element without the '&' - with the ampersands you would pass
pointers to the arrays, not pointers to the first elements. Whil
the addresses passed to the function would be the same, they are
different types and the compiler should warn you about that if you
adjust the warning level to something reasonable.
for(i=0;i<20;i+ +){
printf("%d\n",& pInt[0]);
And this probably should be

printf( "%d\n", pInt[ i ] );

Note that "pInt[i]" is absolutely identical to "*(pInt+i)" (that's
what the compiler is going to convert it to). But then the array you
try (unsuccessfully , see below) to return from search_char() can have
up to 201 elements, so why only print 20 of them? You don't even know
how many of them got set.
return 0;
} int search_char( char *pStr , char *pSearch ) {
Why do you declare this function to return an int when you actually
try to make it return an int pointer?
int i;
int vPossition[201];
for( i=0;i<=200;i++) {
Shouldn't you rather stop when you reach the end of the string,
i.e. when pStr[i] is '\0'? Otherwise you're rather likely to
comparing elements of pStr that never got assigned a value.
if(pStr[i] == pSearch[0]){
printf("Found %c in position %d \n", pStr[i],i+1);
vPossition[i] = i;/*position into array*/
Now, that's probably not what you really want - you only set those
elements of the vPossitions array where there's a match and you leave
the rest of them in some random state. What would that be good for?
You can't figure out afterwards which have been set and which haven't.
}
}
return vPossition;
And this is a plain mistake. You try to return a variable (or array)
local to this function. The moment this function is left, this aray
will stop to existand the calling function can't do nothing at all
with the return value. So here you throw away all the information the
function assembled. If you want to return the array then you must use
one that doesn't vanish once the function is left. You can do that
by either making the array a static array (but note that each new
invocation of the function will overwrite the results from the pre-
vious invocation) or by returning a pointer to some memory you allo-
cated in this function (but then the calling function must take care
of deallocation!).
} BTW. I know my english is not best in the word, so please stop bugging me
about my speling.


Perhaps not too clever an attitude when you expect answers from other
people - spelling can sometimes be rather important to make ones mea-
ning clear and bad spelling definitely makes your questions harder to
read. Do you realize that "speling" gets spelt with two 'l's? ,-)

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Nov 14 '05 #2
Carramba wrote:

hi!

the code is cinpiling with gcc -ansi -pedantic.
so Iam back to my question
Iam trying to make program were I enter string and serach char.
and funktion prints out witch position char is found this
is done if funktion serach_char. so far all good
what I want do next is:
return, from funktion, pointer value to array were
positions ( of found char) is stored. and print that array from main.


/* BEGIN new.c */

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

#define STRING_LENGTH 200
#define SEARCH_LENGTH 20
#define str(x) # x
#define xstr(x) str(x)

int main(void) {
char cStr[STRING_LENGTH];
char cSearch[SEARCH_LENGTH];
int rc;
char *ptr;

puts("Enter a string or enter an empty string to quit.");
rc = scanf("%" xstr(STRING_LEN GTH) "[^\n]%*[^\n]", cStr);
if (!feof(stdin)) {
getchar();
}
while (rc == 1) {
puts("Enter search string or enter an empty string to
quit.");
rc = scanf("%" xstr(SEARCH_LEN GTH) "[^\n]%*[^\n]", cSearch);
if (!feof(stdin)) {
getchar();
}
if (rc != 1) {
break;
}
ptr = strstr(cStr, cSearch);
if (ptr != NULL) {
puts("Search string found.");
puts(ptr);
} else {
puts("Search string not found.");
}
puts("Enter a string or enter an empty string to quit.");
rc = scanf("%" xstr(STRING_LEN GTH) "[^\n]%*[^\n]", cStr);
if (!feof(stdin)) {
getchar();
}
}
return 0;
}

/* END new.c */
--
pete
Nov 14 '05 #3
thanx ! you answer realy helpt! and I got it working!

On Fri, 03 Jun 2005 13:18:27 +0200, <Je***********@ physik.fu-berlin.de>
wrote:
Carramba <no****@note.co m> wrote:
the code is cinpiling with gcc -ansi -pedantic.
You better also use '-W' and '-Wall'...

I ll do it, and se if it's makes me writte better code :)
so Iam back to my question
Iam trying to make program were I enter string and serach char.
and funktion prints out witch position char is found this
is done if funktion serach_char. so far all good
what I want do next is:
return, from funktion, pointer value to array were
positions ( of found char) is stored. and print that array from main.
but I only manage to print memory adress to array..

any suggestions?

#include <stdio.h>
int search_char( char *pStr , char *pSearch );

int main(void){
char cStr[201];
char cSearch[21];
int *pInt;
int i ;
printf("Enter string\n");
scanf("%s", cStr);
printf("Enter search char\n");
scanf("%s", cSearch); /*reading it as string becouse I want
to
by able later search 2 chars and more*/


I hope you understand that this use of scanf() is dangerous - if the
user inputs more non-white-space characters than the char arrays
are long then your program writes past the end of these arrays...
*pInt = search_char( &cStr , &cSearch );


If search_char() would return an int pointer (as it probably should) then
this would have to be written as

pInt = search_char( cStr, cSearch );

Note that all the '*'s and '&'s you are using don't make sense. On
the keft hand side you have a pointer and you want to assign the
return value to that pointer, not to what it's pointing to. On the
right hand side both arrays are already passed by pointer to the
first element without the '&' - with the ampersands you would pass
pointers to the arrays, not pointers to the first elements. Whil
the addresses passed to the function would be the same, they are
different types and the compiler should warn you about that if you
adjust the warning level to something reasonable.
for(i=0;i<20;i+ +){
printf("%d\n",& pInt[0]);


And this probably should be

printf( "%d\n", pInt[ i ] );


yes, my misstake
Note that "pInt[i]" is absolutely identical to "*(pInt+i)" (that's
what the compiler is going to convert it to). But then the array you
try (unsuccessfully , see below) to return from search_char() can have
up to 201 elements, so why only print 20 of them? You don't even know
how many of them got set. the reason of only 20 is for testing purposes, it was enought to se if
prog. was runing corect
return 0;
}

int search_char( char *pStr , char *pSearch ) {


Why do you declare this function to return an int when you actually
try to make it return an int pointer?

I did'n realise that! but thanx for pointing it out!
int i;
int vPossition[201];
for( i=0;i<=200;i++) {


Shouldn't you rather stop when you reach the end of the string,
i.e. when pStr[i] is '\0'? Otherwise you're rather likely to
comparing elements of pStr that never got assigned a value.
if(pStr[i] == pSearch[0]){
printf("Found %c in position %d \n", pStr[i],i+1);
vPossition[i] = i;/*position into array*/

and you are right again!
Now, that's probably not what you really want - you only set those
elements of the vPossitions array where there's a match and you leave
the rest of them in some random state. What would that be good for?
You can't figure out afterwards which have been set and which haven't.
}
}
return vPossition;


And this is a plain mistake. You try to return a variable (or array)
local to this function. The moment this function is left, this aray
will stop to existand the calling function can't do nothing at all
with the return value. So here you throw away all the information the
function assembled. If you want to return the array then you must use
one that doesn't vanish once the function is left. You can do that
by either making the array a static array (but note that each new
invocation of the function will overwrite the results from the pre-
vious invocation) or by returning a pointer to some memory you allo-
cated in this function (but then the calling function must take care
of deallocation!).
}

BTW. I know my english is not best in the word, so please stop bugging
me
about my speling.


Perhaps not too clever an attitude when you expect answers from other
people - spelling can sometimes be rather important to make ones mea-
ning clear and bad spelling definitely makes your questions harder to
read. Do you realize that "speling" gets spelt with two 'l's? ,-)

Regards, Jens

well, I have wrote that after some people on group have buggt me to much
about it! I'am trying my best
--

Thanx in advance
_______________ _________
BTW. I know my english is not best in the word, so please stop bugging me
about my spelling. And yes Iam sorry you don't understand what I mean, but
there is no point to yell at me. Have a nice day.

Nov 14 '05 #4

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

Similar topics

7
7290
by: BrianJones | last post by:
Hi, if you have a function, how is it possible to return an array? E.g.: unsigned long function(...) // what I want to do, obviously illegal I do know such would be possible by using a dynamic array e.g: array *a; a = function(...)
5
3077
by: Gent | last post by:
I have two questions which are very similar: Is it possible to return an object in C++. Below is part of my code for reference however I am more concerned about the concept. It seems like the function below is returning a pointer to pointers who are GUID. I am trying to write a wrapper to use in my VB code and what I would prefer to do is be able to return an array of GUID. I remember (not sure) that the concept of arrays does not really...
10
10279
by: Fraser Ross | last post by:
I need to know the syntax for writing a reference of an array. I haven't seen it done often. I have a class with a member array and I want a member function to return an reference to it. Returning a pointer to the first element might do but I want to do what I've said. Fraser.
41
3786
by: Materialised | last post by:
I am writing a simple function to initialise 3 variables to pesudo random numbers. I have a function which is as follows int randomise( int x, int y, intz) { srand((unsigned)time(NULL)); x = rand(); y = rand();
10
3148
by: Pete | last post by:
Can someone please help, I'm trying to pass an array to a function, do some operation on that array, then return it for further use. The errors I am getting for the following code are, differences in levels of indirection, so I feel it must have something to do with the way I am representing the array in the call and the return. Below I have commented the problem parts. Thanks in advance for any help offered. Pete
17
3233
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);
9
1868
by: josh | last post by:
Hi, I'm converting (for learning purpose) )a program from Java to C++ and I've a doubt: In Java every argument (variable and reference types) is passed and returned in functions by-value so if I want to create inside that function a matrix (i.e. int a) and than passing the reference to it I can simply returning that value: in main()
8
2206
by: darren | last post by:
Hi everybody, have a quick look at this code: ===== ===== int main(void) { string msg; makeString(msg); cout << "back in main, result = " << msg << endl;
5
2674
by: ctj951 | last post by:
I have a very specific question about a language issue that I was hoping to get an answer to. If you allocate a structure that contains an array as a local variable inside a function and return that structure, is this valid? As shown in the code below I am allocating the structure in the function and then returning the structure. I know if the structure contained only simple types (int, float) this will work without problems as you...
0
8059
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
8495
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
8470
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...
1
8145
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8330
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...
0
5475
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
3960
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
2474
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
0
1328
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.