473,574 Members | 2,817 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cannot return values of char variable

Hi there once more........

Instead of showing all the code my problem is simple.

I've tried to create this function:

char temp(char *string){

alterString(str ing);
return string;
}

char alterString(cha r *string){}

temp receives a string and uses the alterString to modify it.

My issue is simple, when i pass the argument string to alterString it
appears in the function alterString has being empty.

I've tried changing the signatures of the functions to
char temp(char string){
char alterString(cha r string){}
but the issue still occurs......
Can please somebody give me just a little example of the working
function....... ... it would really help.....

thanks in advance for every support you have given to me this night.

Nov 3 '06 #1
18 4033
Pedro Pinto wrote:
Hi there once more........

Instead of showing all the code my problem is simple.

I've tried to create this function:

char temp(char *string){

alterString(str ing);
return string;
}
This function is defined as returning a char, but it is trying to
return a char *.
char alterString(cha r *string){}

temp receives a string and uses the alterString to modify it.

My issue is simple, when i pass the argument string to alterString it
appears in the function alterString has being empty.
Maybe it was empty when passed to temp. There is no way to tell
from what you have given. Create a small, complete program that
displays the problem, and post it. Then people might be able to
help.

--
Thomas M. Sommers -- tm*@nj.net -- AB2SB

Nov 3 '06 #2
Pedro Pinto wrote:
Hi there once more........

Instead of showing all the code my problem is simple.

I've tried to create this function:

char temp(char *string){

alterString(str ing);
return string;
}
'string' is a char *; your function returns a char.
Nov 3 '06 #3
Ok here it goes:

The problem is, when the function menu starts, i insert the information
CREATE TABLE [tab] col1,col2,col3

that starts the function criaRespCreate and the buf variable, when
exported into the program, before is ok, i print it to the screen and
appears well, but when returned it comes empty.......

I start the client socked, the result of the printf's:

sd075@lab1215-31:~/Desktop/teste/Cliente$ ./clisql 17500
Sintaxe do programa cliente:
clisql -s <endereço_servi dor<porto_servi dor>
-endereço_servid or: (opcional) IP do servidor
-porto_servidor: porto do servidor
Insira comando:
CREATE TABLE [tab] col1,col2,col3
1 - buffer =

2 - buffer =

passei o primeiro divide com aux[0] = CREATE TABLE

passei o primeiro divide com aux[1] = tab] col1,col2,col3
passei o segundo divide com aux[0] = tab

passei o segundo divide com aux[1] = col1,col2,col3
dpx do memcpy aux[0] = tab

dpx do memcpy aux[1] = col1,col2,col3
buffer =

antes do strcpy - aux[1] =

argv[0] = (null)
No test to search.


Code --------------------------
cliente_aux.c

#include "cli.h"
void syntax() {

printf("Sintaxe do programa cliente:\n");

printf(" clisql -s <endereço_servi dor>
<porto_servidor >\n");

printf(" -endereço_servid or: (opcional) IP do
servidor\n");

printf(" -porto_servidor: porto do servidor\n");

}

void sintaxe(){
printf("Sintaxe do programa cliente:\n");

printf("CREATE TABLE [table_name] coluna1,coluna2 ,coluna3...\n") ;

printf("INSERT INTO [table_name] VALUES
(coluna1_value, coluna2_value,c oluna3_value... ) \n");

printf("UPDATE [table_name] SET (Coluna) WHERE (expressao)\n") ;
printf("SELECT [Coluna] FROM (table_name) WHERE (expressao)\n") ;

}

char menu(){

char buf[BUFFSIZE];
char bufSaida[BUFFSIZE];

char *tmp = buf;
int cod = 0;
int id = random();
int tamanhoMsg;

printf("Insira comando:\n");

// le uma linha de input
if (fgets(buf,size of(buf),stdin) == NULL)
perror("fgets") ;

char comando[10];
memset(comando, 0,sizeof(comand o));
if (sscanf(buf,"%9 s",comando) < 1)
perror("scanf") ;

if (strncmp(buf,"C REATE",6) == 0){
cod = 11;

tamanhoMsg = criaRespCreate( cod,id, buf,bufSaida);
}
else if(strncmp(buf, "INSERT",6) == 0){
cod = 12;
//buffer =criaRespInsert (cod,id, buf);
}
else if(strncmp(buf, "UPDATE",6) == 0){
cod = 13;
//buffer =criaRespUpdate (cod,id, buf);
}
else if(strncmp(buf, "SELECT",6) == 0){
cod = 14;
//buffer =criaRespSelect (cod,id, buf);
}
else if(strncmp(buf, "QUIT",4) == 0){
exit(0);
}
else { printf("Comando Desconhecido\n" );
}
return bufSaida;
}

int criaRespCreate( int cod, int id, char *argv, char *buffer){

int tam = 0;
int nRows = 0;
char *aux[strlen(argv)];
char str[]=" // ";
int h = 0;
//tamanho do caracter delimitador
int tcd = strlen(str);

// inserir codigo

memcpy(buffer,& cod,LENGTH);
tam += LENGTH;

printf("1 - buffer = %s\n", buffer);

// inserir caracter delimitador //
memcpy(buffer+t am,&str,strlen( str));
tam += tcd;

printf("2 - buffer = %s\n", buffer);
// inserir id da mensagem
memcpy(buffer+t am, &id, LENGTH);
tam += LENGTH;

// inserir caracter delimitador //
memcpy(buffer+t am,&str,strlen( str));
tam += tcd;

// dividir string e inserir nome tabela
divide(argv,aux ,"[");

printf("passei o primeiro divide com aux[0] = %s\n\n", aux[0]);
printf("passei o primeiro divide com aux[1] = %s\n\n", aux[1]);

memset(argv,0,s trlen(aux));
strcpy(argv,aux[1]);
memset(aux,0,st rlen(argv));
divide(argv,aux ,"]");

printf("passei o segundo divide com aux[0] = %s\n\n", aux[0]);
printf("passei o segundo divide com aux[1] = %s\n\n", aux[1]);
memcpy(buffer+t am,&aux[0],strlen(aux[0]));
tam += strlen(aux[0]);
printf("dpx do memcpy aux[0] = %s\n\n", aux[0]);
printf("dpx do memcpy aux[1] = %s\n\n", aux[1]);
// inserir caracter delimitador
memcpy(buffer+t am,&str,strlen( str));
tam += tcd;
printf("buffer = %s\n", buffer);

// inserir numero e nome colunas

memset(argv,0,s trlen(aux[1]));
printf("antes do strcpy - aux[1] = %s\n\n", aux[1]);
strcpy(argv,aux[1]);
printf("argv[0] = %s\n", argv[0]);
memset(aux,0,st rlen(argv));
divide(argv,aux ,",");

printf("passei o terceiro divide com aux[0] = %s\n\n", aux[0]);
printf("passei o terceiro divide com aux[1] = %s\n\n", aux[1]);
printf("passei o terceiro divide com aux[2] = %s\n\n", aux[2]);

printf("str(aux ) = %d\n", strlen(aux));
// inserir numero de colunas
for(h=0; aux[h]!=NULL;h++){
nRows++;
}

memcpy(buffer+t am, nRows, LENGTH);
tam += LENGTH;

// inserir caracter delimitador
memcpy(buffer+t am,&str,strlen( str));
tam += tcd;
// inserir colunas

for(h=0; aux[h]!=NULL;h++){
memcpy(buffer+t am,&aux[h],strlen(aux[h]));
tam += tcd;
// inserir caracter delimitador
memcpy(buffer,& str,strlen(str) );
tam += tcd;

}
return buffer;
}
-------------------------------------------

clisql.c--------------


#include "cli.h"


/* Funcao Main */

int main (int argc, char *argv[]) {

syntax();
/* Funcaoo que apresenta sintaxe do programa */



int sock;

int broadcast = 1;

struct sockaddr_in server;

struct sockaddr_in cli;

int porto_servidor;
char buffer[BUFFSIZE];
char *tmp = buffer;
tmp = buffer;

char input[1024];
/* Limpa a estrutura */

bzero((char *)&server, sizeof(server)) ;

bzero((char *)&cli, sizeof(cli));

/* Limpar o buffer */

memset(buffer, 0, BUFFSIZE);
input[0] = menu(buffer);

/* Criacao da socket */

if ((sock = socket(AF_INET, SOCK_DGRAM,0)) <0) {

perror("socket" );

exit(1);

}

else {

printf("Cliente : socket criada \n");

}

/* Verificar ip */
if(strcmp(argv[1], "-s") == 0) {

printf("entrei n o verifica ip, estamos a funcionar com endereco ip
inserido\n");

inet_aton(argv[2], &server.sin_add r);
porto_servidor = atoi(argv[3]);
}

else {//enviar em broadcast

printf("Não foi fornecido o endereço IP, a enviar em broadcast\n");

porto_servidor = atoi(argv[1]);
server.sin_addr .s_addr = htonl(INADDR_BR OADCAST);
/* Activar broadcast na socket */

if (setsockopt(soc k, SOL_SOCKET, SO_BROADCAST, (char*)&broadca st,
sizeof (int)) <0) {

perror("setsock opt");

exit(1);

}

}
/* verifica se a porta esta entre os valores pretendidos,

* visto o número de grupo ser o 75, port vai variar entre

* 17500 e 17599 */
void checkPort(porto _servidor) {

if(porto_servid or < 17500 || porto_servidor 17599) {

printf("Cliente : O porto tem de ser entre 17500 e 17599!\n");

exit(-1);

}

}



/* Definir a familia de protocolo e porto */

server.sin_fami ly = AF_INET;

server.sin_port = htons(porto_ser vidor);


/* Inicio da comunicacao com o servidor */




/* Enviar a mensagem para o servidor*/

if(sendto(sock, tmp, strlen(buffer), 0, (struct sockaddr *)&server,
sizeof(server)) <0) {

perror("sendto\ n");

exit(1);

}

else {

printf("Cliente : Mensagem enviada com sucesso\n");

}

while(1){
printf("entrei no while\n");

/* timeout de 10 segundos */
struct timeval timeout;
timeout.tv_sec = 10; //segundos

timeout.tv_usec = 0; //microsegundos

fd_set readfds;

int sel;

// char buf1[64];

/* limpar a fd_set */

FD_ZERO(&readfd s);

/* colocar o file descriptor no fd_set */

FD_SET(sock, &readfds);

printf("vou ver agora o select\n");

if((sel = select(sock+1, &readfds, NULL, NULL, &timeout)) <0)
perror("select\ n");


else if (sel == 0){

printf("Ocorreu um timeout! Nao foi recebida nenhuma mensagem em
10s.\n");

exit(0);
}

memset(buffer,0 ,BUFFSIZE);
printf("vou agora ler a resposta do servidor\n");

/* ler a resposta do servidor */

if(recvfrom(soc k, buffer, BUFFSIZE, 0, NULL, NULL) < 0) {
printf("entrei no recv por ser < 0\n");

perror("recvfro m\n");

exit(1);

}

else {

printf("Cliente : Mensagem recebida com sucesso\n");

printf("buffer = %s\n", buffer);
exit(0);
}

}

/* fecho da socket */

close(sock);
}


----------------------cli.h--------------------------------------

#ifndef CLI_H
#define CLI_H

#include "projecto.h "
/* Definicao das funcoes definidas em cliente_aux.c */

void syntax();

char menu();

int criaRespCreate( int cod, int id, char *argv, char *buffer);



#endif

--------------------------projecto.h----------------------------------------
#ifndef PROJECTO_H

#define PROJECTO_H

#define BUFFSIZE 6804
#define LENGTH 4

/* Bibliotecas necessarias */

#include <sys/socket.h>

#include <sys/types.h>

#include <stdio.h>

#include <errno.h>

#include <sys/time.h>

#include <stdlib.h>
#include <arpa/inet.h>

#include <netinet/in.h>

#include <netdb.h>
#include <string.h>

#endif

Nov 3 '06 #4

Pedro Pinto wrote:
Hi there once more........

Instead of showing all the code my problem is simple.
OK - so give us a simple testcase.
I've tried to create this function:

char temp(char *string){

alterString(str ing);
return string;
}

char alterString(cha r *string){}

temp receives a string and uses the alterString to modify it.
OK - so write a minimal testcase which uses these functions to work
with a string, show us the whole code (cut and paste, don't retype),
tell us what input you gave it, what output you expected and what
output you got. Then we've got something to work on.

Here's the sort of thing I mean (this is just an example, which I
didn't expect to work) :-

#include <stdlib.h>
#include <stdio.h>

char alterString(cha r *string){}

char temp(char *string){

alterString(str ing);
return string;
}

int main(void) {

char myString[]="Hello Pedro";
printf("I started with [%s]\n",myString) ;

printf("I got [%s]\n",temp(myStri ng));

return EXIT_SUCCESS;
}
When I compiled it, I had this warning from gcc:-
pedro.c: In function `temp':
pedro.c:9: warning: return makes integer from pointer without a
cast

When I ran it, this happened:-
./pedro
I started with [Hello Pedro]
Segmentation fault

Which is fair - temp() returns a char, not a char *, but I told printf
to treat it as the address of (the first of) a null-terminated set of
characters.

I think part of your problem is that temp() and alterString() should be
declared as returning char *, not char, but beyond that - who knows?

Nov 3 '06 #5
Pedro Pinto wrote:
Ok here it goes:
[unnecessary detail snipped]

What part of Thomas Sommers' message - "Create a small, complete
program that
displays the problem, and post it." - don't you understand?

You said your problem was with two small functions, so write a small
program that just contains those functions and enough code (in a main()
function) to test them. This is, IMHO, basic programming craft...

Nov 3 '06 #6
Ok, here it goes.

The problem is that i cannot, like in this example, return a char[]
correctly.

in this case i have do create a void function.

Although *array[] param keeps the alteration made to it i cannot do
this function with this signature:

char divide(char search_string[], char *array[], char *delimiter)

and return correctly the string.
Can you give me some tips on how i could return a string (or char
array) in this divide function?

Thank for all the help!
--------------------------------------------
void divide(char search_string[], char *array[], char *delimiter){

int loop;

array[0]=strtok(search_ string,delimite r);

if(array[0]==NULL)

{

printf("No test to search.\n");

exit(0);

}

for(loop=1;loop <50;loop++)

{

array[loop]=strtok(NULL,de limiter);

if(array[loop]==NULL)

break;

}

for(loop=0;loop <50;loop++)

{

if(array[loop]==NULL)

break;

//printf("\nDivid e - array[%d] = %s", loop,array[loop]);

}

}

Nov 3 '06 #7

Pedro Pinto wrote:
Ok, here it goes.

The problem is that i cannot, like in this example, return a char[]
correctly.

in this case i have do create a void function.

Although *array[] param keeps the alteration made to it i cannot do
this function with this signature:

char divide(char search_string[], char *array[], char *delimiter)
(Yet again) That function would be have to return a single character.

If you want to return a string, you must return a pointer to the first
character of the null delimited array of characters - e.g. char
*divide(...).

If you want to return an array of strings, meaning an array of pointers
to null-delimited arrays of characters, using char **divide() would be
appropriate.

Nov 3 '06 #8
Pedro Pinto wrote:
Ok, here it goes.
<problem description and code snippet sniped>

For your implementation of the divide function , i have created the
following test case (which I guess was what Mark was asking you to do).

#include <stdio.h>
#include <stdlib.h>

void divide(char search_string[], char *array[], char *delimiter){
int loop;
array[0]=strtok(search_ string,delimite r);

if(array[0]==NULL)
{
printf("No test to search.\n");
exit(0);
}

for(loop=1;loop <50;loop++)
{
array[loop]=strtok(NULL,de limiter);

if(array[loop]==NULL)
break;
}

for(loop=0;loop <50;loop++)
{
if(array[loop]==NULL)
break;
//printf("\nDivid e - array[%d] = %s", loop,array[loop]);
}
}

int main(void) {
int i = 0 ;
char *arr[50];

divide("this,is ,comma,separate d,string", arr ,",");

printf("Divided contents\n");
for(i = 0; i < 50; i++)
{
if(arr[i]==NULL)
break;

printf("%s \n", arr[i]);
}
return 0;
}

Compilation :

Microsoft (R) 32-bit C/C++ Standard Compiler Version 13.00.9466 for 80x86
Copyright (C) Microsoft Corporation 1984-2001. All rights reserved.

sample.c
sample.c(6) : warning C4047: '=' : 'char *' differs in levels of
indirection from 'int'
sample.c(16) : warning C4047: '=' : 'char *' differs in levels of
indirection from 'int'
Microsoft (R) Incremental Linker Version 7.00.9466
Copyright (C) Microsoft Corporation. All rights reserved.

/out:sample.exe
sample.obj

Execution Result :

Divided contents
this
is
comma
separated
string

I am not sure what you want to return from divide function.

--
Prasad
Nov 3 '06 #9

Prasad escreveu:
Pedro Pinto wrote:
Ok, here it goes.
<problem description and code snippet sniped>

For your implementation of the divide function , i have created the
following test case (which I guess was what Mark was asking you to do).

#include <stdio.h>
#include <stdlib.h>

void divide(char search_string[], char *array[], char *delimiter){
int loop;
array[0]=strtok(search_ string,delimite r);

if(array[0]==NULL)
{
printf("No test to search.\n");
exit(0);
}

for(loop=1;loop <50;loop++)
{
array[loop]=strtok(NULL,de limiter);

if(array[loop]==NULL)
break;
}

for(loop=0;loop <50;loop++)
{
if(array[loop]==NULL)
break;
//printf("\nDivid e - array[%d] = %s", loop,array[loop]);
}
}

int main(void) {
int i = 0 ;
char *arr[50];

divide("this,is ,comma,separate d,string", arr ,",");

printf("Divided contents\n");
for(i = 0; i < 50; i++)
{
if(arr[i]==NULL)
break;

printf("%s \n", arr[i]);
}
return 0;
}

Compilation :

Microsoft (R) 32-bit C/C++ Standard Compiler Version 13.00.9466 for 80x86
Copyright (C) Microsoft Corporation 1984-2001. All rights reserved.

sample.c
sample.c(6) : warning C4047: '=' : 'char *' differs in levels of
indirection from 'int'
sample.c(16) : warning C4047: '=' : 'char *' differs in levels of
indirection from 'int'
Microsoft (R) Incremental Linker Version 7.00.9466
Copyright (C) Microsoft Corporation. All rights reserved.

/out:sample.exe
sample.obj

Execution Result :

Divided contents
this
is
comma
separated
string

I am not sure what you want to return from divide function.

--
Prasad

I can do that inside main. What i can't do is with divide:

char divide(char search_string[], char *array[], char *delimiter)

and return the string you printed! Can this be done?

Nov 3 '06 #10

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

Similar topics

7
1930
by: Ramiro Barbosa, Jr. | last post by:
All, Any ideas why the following code prints zeros for the message id, number of packets and sequence number as shown in the sample output below? Somehow I am not being able to access the contents of my 'incomingDataBuffer' array. I have also included some values from the respective MSVC 6.0 debug session. Thank you!
20
37358
by: Brad Eck | last post by:
"The only operators that cannot be overloaded are :: (scope resolution), . (member selection), and .* (member selection through pointer to function). Quoting from Stroustrup's 3rd edition of _The C++ Programming Language_, section 11.2 (page 263), these three operators 'take a name, rather than a value, as their second operand and provide...
8
5460
by: baustin75 | last post by:
Posted: Mon Oct 03, 2005 1:41 pm Post subject: cannot mail() in ie only when debugging in php designer 2005 -------------------------------------------------------------------------------- Hello, I have a very simple problem but cannot seem to figure it out. I have a very simple php script that sends a test email to myself. When I...
10
4438
by: Jean-David Beyer | last post by:
I have some programs running on Red Hat Linux 7.3 working with IBM DB2 V6.1 (with all the FixPacks) on my old machine. I have just installed IBM DB2 V8.1 on this (new) machine running Red Hat Enterplise Linux 3 ES, and applied FixPack fp5_mi00069.tar to it. After creating an instance, starting the database, creating a database, and entering...
6
6598
by: Neo | last post by:
Dear All, I want to know how a subroutine should return an array of values to the main program. From the main program, I call a sub-routine 'get_sql' which then fetches data from oracle db using oci8 routines. The output resides in a structure defined within the sub-routine. Now I want this structure to be returned to main program so that I...
17
2124
by: Gladiator | last post by:
When I am trying to execute a program from "The C Programming Language" by Dennis Ritchie, I tried to run the following program.I am using Dev++ as a compiler software. The Program is presented below. #include <stdio.h> main() { long nc;
26
2871
by: Martin Jørgensen | last post by:
Hi, I don't understand these errors I get: g++ Persort.cpp Persort.cpp: In function 'int main()': Persort.cpp:43: error: name lookup of 'j' changed for new ISO 'for' scoping Persort.cpp:37: error: using obsolete binding at 'j'
5
5027
by: wong_powah | last post by:
#include <vector> #include <iostream> using std::cout; using std::vector; enum {DATASIZE = 20}; typedef unsigned char data_t;
45
18823
by: Zytan | last post by:
This returns the following error: "Cannot modify the return value of 'System.Collections.Generic.List<MyStruct>.this' because it is not a variable" and I have no idea why! Do lists return copies of their elements? Why can't I change the element itself? class Program { private struct MyStruct
0
7747
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...
0
8093
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. ...
0
8129
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...
0
6498
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...
1
5643
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...
0
5331
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...
0
3785
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2262
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
1094
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...

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.