473,663 Members | 2,903 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C newbie array question

2 New Member
Hi,

Can anbody tell me why the below code outputs abbrev for all the arrays values in vals? What is the correct way to assign values so that when I iterate through the array I will get the seperate values?

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. const char *toksplit(const char *src, /* Source of tokens */
  5. char tokchar, /* token delimiting char */
  6. char *token, /* receiver of parsed token */
  7. size_t lgh) /* length token can receive */
  8. /* not including final '\0' */
  9. {
  10. if (src) {
  11. while (' ' == *src) *src++;
  12.  
  13. while (*src && (tokchar != *src)) {
  14. if (lgh) {
  15. *token++ = *src;
  16. --lgh;
  17. }
  18. src++;
  19. }
  20. if (*src && (tokchar == *src)) src++;
  21. }
  22. *token = '\0';
  23. return src;
  24. } /* toksplit */
  25.  
  26. #define ABRsize 6 /* length of acceptable token abbreviations */
  27.  
  28. char *vals[4];
  29.  
  30. int main(void)
  31. {
  32. char teststring[] = "This is a test, ,, abbrev, more";
  33.  
  34. const char *t, *s = teststring;
  35. int i;
  36. char token[ABRsize + 1];
  37.  
  38. puts(teststring);
  39. t = s;
  40. for (i = 0; i < 4; i++) {
  41.     t = toksplit(t, ',', token, ABRsize);
  42.     putchar(i + '1'); putchar(':');
  43.     vals[i] = token;
  44.     puts(token);
  45. }
  46.  
  47. puts("-----------------------------------");
  48.  
  49. for (i = 0; i < 4; i++) {
  50.     putchar(i + '1'); putchar(':');
  51.     puts(vals[i]);
  52. }
  53.  
  54. return 0;
  55. }
  56.  
Thanks
Angus
Oct 1 '08 #1
4 1270
vekipeki
229 Recognized Expert New Member
Your vals array is an array of pointers to char. They all point to the same place in memory, the beginning of your token array.

You can see that you only allocate your 6+1 bytes for tokens once (char token[ABRsize + 1]), so you cannot expect to have 4 tokens in memory - on each call to toksplit, you are passing the pointer to your one and only token.

So the answer is:
1. Get rid of token
2. Allocate 4 tokens when allocating vals:
Expand|Select|Wrap|Line Numbers
  1. char vals[4][ABRsize + 1];
  2.  
3. When calling toksplit, pass vals[i] directly:
Expand|Select|Wrap|Line Numbers
  1. t = toksplit(t, ',', vals[i], ABRsize);
  2.  
Oct 1 '08 #2
angusmiller
2 New Member
Thanks worked a charm! one more thing I need to be able to "reset" the vals array, can I do this without having to loop through the array like below?

Expand|Select|Wrap|Line Numbers
  1. for (i = 0; i < 4; i++) {
  2.     strcpy(vals[i],"");
  3. }
  4.  
Thanks
Oct 1 '08 #3
vekipeki
229 Recognized Expert New Member
If you want to set all items of your vals array to an empty string, this is the way to do it. You could even do it at the beginning of your program to ensure that all your strings are null-terminated.
Oct 10 '08 #4
Tassos Souris
152 New Member
You can also use the memset() function:
Expand|Select|Wrap|Line Numbers
  1.  memset( destination, value, size );
  2.  
Oct 10 '08 #5

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

Similar topics

8
3157
by: scythetleppo | last post by:
I am new thanks for the help. I have a text file set up like this: word1a<tab>word2a<tab>word3a<tab>word4a word1b<tab>word2b<tab>word3b<tab>word4b word1c<tab>word2c<tab>word3c<tab>word4c I want a php program that compares a date and removes a line if the date is past. Please don't say to use cron or just throw a function at me, I really am super new =]
5
1617
by: traviswhiskey | last post by:
so i'm trying to read in from a file but having lots of trouble so far all i get are segmentation faults or jibberish numbers when outputting and i just need a little bit of direction on how to solve this problem. i'm reading i don't have much experience with reading arrays in from a file and stuff. heres what i have. struct date { int day, month, year; }; struct student { string firstName, lastName;
1
2379
by: sheephead86 | last post by:
Hi, I'm pretty new to java, and I have a small problem involving drawing a rectangle on a java applet.Firstly this is not a plea for someone to help me with this peice of work, I just need pointing in the right direction. Ok the problem. I am creating a program that ask the user to input a height value, the program will then do a calculation and create a golden ratio width. The type of both the height and the width are double. This is...
2
1000
by: MikeB | last post by:
Just started a course on PHP and we're doing stuff with mySQL. On this page: http://us.php.net/manual/en/function.mysql-fetch-array.php In example 2, there are these lines: while ($row = mysql_fetch_array($result, MYSQL_NUM)) { printf("ID: %s Name: %s", $row, $row); What is the %s - a variable into the array or something?
2
1511
by: Damfino | last post by:
Hi all, Newbie question here wrt defining a class that will work on bits read from a binary file. How would you go about doing it? As an example please look at the structure of my data given below. The data comes in 40 byte packets via stdin or a binary file. my_Data_pkt(){ syncByte (8bits) XML_type (2bits) XML_subtype (2bits) record_value (3bits)
12
1838
by: Philipp.Weissenbacher | last post by:
Hi all! This is most certainly a total newbie question, but why doesn't the following code cause a segfault? void insertion_sort(int a, int length) { int i; for (i=0; i < length; i++) { int j, v = a;
10
1400
by: Mladen Gogala | last post by:
I am a Python newbie who decided to see what that Python fuss is all about. Quite frankly, I am a bit perplexed. After having had few months of experience with Perl (started in 1994 with Perl v4, and doing it ever since) , here is what perplexes me: perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' The equivalent in Python looks like this: Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51)
33
7163
by: Adam Chapman | last post by:
Hi, Im trying to migrate from programming in Matlab over to C. Im trying to make a simple function to multiply one matrix by the other. I've realised that C can't determine the size of a 2d array, so im inputting the dimensions of those myself. The problem is that the output array (C=A*B) has as many rows as A and as many columns as B. I would think of initialising C with:
6
3329
by: Anil Gupte/iCinema.com | last post by:
I am very new to C++ (Actually have dabbled in it before but nevermind). This is my first appliccation that I started from scratch. I created a Console Application in VC 2005 and this is what I have so far: using namespace System; using namespace System::IO; #include "stdafx.h" int _tmain(int argc, _TCHAR* argv)
1
2967
by: sixtyfootersdude | last post by:
Good Morning! I am a perl newbie and I think that I am struggling with references. I have an array of references to hashes which I am trying to print. This is what I have: for(my $i=0; $i<@input; $i++){ my $hash = $input; print "$i: \n";
0
8436
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
8345
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8771
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
7371
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...
0
5657
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
4349
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2763
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
2
2000
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1757
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.