468,512 Members | 1,445 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,512 developers. It's quick & easy.

Storage strings in an array

2
Hi all:

I am new here as in C.
I want to store some strings in an array and i did, but when I show in the screen
only shows me the last string i introduce, here is my C source code:

#include "stdio.h"
#define LENG 45;
char *readString(char *string,int n); // function where read a string and return it
int main(void){
char string[LENG+1] , *ptrString[3];
int conunter;

// Here i am storing

for(counter=0;counter<3;counter++){
printf("String %d: ",counter+1);
ptrString[counter]=readS(string,LENG);//Storing in my string array
}

//Here i send to print in screen the array of strings

for(counter=0;counter<3;counter++){
printf("String[%d]: %s\n",counter+1,ptrString[counter]);
}

return 0;
}

//Here is readS

char *readS(char *string, int n){
char c;
int i=0;
while(1){
car=getchar();
if(car==' \n ' || i>n ) break;
string[i]=car;
i++;
}
string[i]=' \0 ' ;
return string;
}
/*
ok if i make this

String 1: Hi
String 2: how
String 3: are

show this

String 1: are
String 2: are
String 3: are
*/

Please help me.
Krann.
Jul 22 '06 #1
2 3202
D_C
293 100+
I've had that happen before, and the reason why is because I did not properly declare the amount of memory needed.

After reading your code, it looks like you are passing and returning the address to the same variable. In effect, all three pointers in ptrString are all pointing to char string[46] that you have declared. You are overwriting the string itself.

To remedy, you need to declare a new character string in the readS subroutine and return that instead of the pointer to char string[46] that you pass into the routine.
Jul 22 '06 #2
Krann
2
Thanx so much D_C.
Jul 22 '06 #3

Post your reply

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

Similar topics

5 posts views Thread by aneesh | last post: by
10 posts views Thread by Ian Todd | last post: by
13 posts views Thread by S.Tobias | last post: by
10 posts views Thread by Duncan M Gunn | last post: by
17 posts views Thread by Christoph Scholtes | last post: by
7 posts views Thread by StupidScript | last post: by
14 posts views Thread by Richard Harter | last post: by
13 posts views Thread by GeezerButler | last post: by
reply views Thread by NPC403 | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.