ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Hello... i've started to learning C and i have a litle problem.
Lets say that i want to create an array to holds strings
eg. "January","February","March"
In C i have to create an array with pointers on it that point to another array each.. eg.
-----------------------------------------------------------------------
#include <stdio.h>
int main() {
char *array[4]; // the array i want
int i;
for (i=0;i<=3;++i) //Reading the data to the array
scanf("%s",array[i]); //eg.January
for (i=0;i<=3;++i)
printf("%s\n",array[i]) //printing the Data
//eg. January
// February
// March
return(0);
}
-----------------------------------------------------------------------
In the above code sth is going wrong. The results are not correct like the program doesn't shows the months correctly.
This has to do with the reading or with the printing ?
I'm i using the pointers the wrong way ??
please help. Thx A Lot !
Your createing an array of pointers, but the pointers themselves are not set to anything.
The scanf function is trying to place information into the address that the pointers point to, it does not change the pointers to point at a new c string. try using this as the array statement.
i just wander , is there any way to do it using an array of pointers instead of a 2D array ??
If there isn't one that means that this code:
<< char *array[]={"ONE","TWO","THREE"}; >>
works only that way, i mean that i must store my strings to the array as above and then to access the array like "array[i]"
I can't load the array data at run time with scanf("%s",array[i]).
i just wander , is there any way to do it using an array of pointers instead of a 2D array ??
Sure but you will need to initialise the pointer and ensure that the pointer points to sufficient memory. Take a look at the malloc() and free() functions.
POOR (doesn't allocate memory for strings, will probably crash):
Code:
#include <stdio.h>
int
main (int argc, char *argv[])
{
/* BAD: We're only allocating pointers, not the strings
being pointed to! */
char *array[4];
int i;
/* Reading the data to the array */
for (i=0; i<=3; i++)
{
scanf("%s", array[i]);
}
/* printing the Data (eg. January, February, March, ...) */
for (i=0; i<=3; i++)
{
printf("%s\n",array[i]);
}
/* Done */
return 0;
}
BETTER: (allocates a fixed # of fixed-length strings):
Code:
#include <stdio.h>
#include <strings.h>
#define NMONTHS 3
#define MAXLEN 10
#define STRIP(a) (a[strlen(a)-1] = '\0')
int
main (int argc, char *argv[])
{
/* BETTER: this allocates both the pointers (months[NMONTHS])
and space for the strings (months[][MAXLEN+1]) */
char months[NMONTHS][MAXLEN+1];
int i;
/* Reading the data to the array */
for (i=0; i<NMONTHS; i++)
{
printf ("Enter next month: ");
fgets (months[i], MAXLEN, stdin);
STRIP (months[i]);
}
/* printing the Data (eg. January, February, March, ...) */
for (i=0; i<NMONTHS; i++)
{
printf("months[%d]: %s\n", i, months[i]);
}
/* Done */
return 0;
}
SAMPLE OUTPUT:
Quote:
Enter next month: Jan
Enter next month: Feb
Enter next month: Mar
months[0]: Jan
months[1]: Feb
months[2]: Mar
BETTER: (Allocates as needed, no built-in limits on #/entries):
Code:
#include <stdio.h>
#include <strings.h>
#define NMONTHS 3
#define MAXLEN 10
#define STRIP(a) (a[strlen(a)-1] = '\0')
int
main (int argc, char *argv[])
{
char *months[MAXLEN+1];
char buff[MAXLEN+1];
int i;
int nmonths = 0;
/* Reading the data to the array */
for ( ;; )
{
printf ("Enter next month, or \"<Enter>\" to exit: ");
fgets (buff, MAXLEN, stdin);
if (strlen (buff) <= 1)
{
printf ("End of data entry!\n");
break;
}
months[nmonths] = (char *)malloc (strlen (buff));
if (!months[nmonths])
{
printf ("ERROR: Unable to alloc memory!\n");
break;
}
else
{
STRIP (buff);
strcpy (months[nmonths++], buff);
}
}
/* printing the Data (eg. January, February, March, ...) */
for (i=0; i<nmonths; i++)
{
printf("months[%d]: %s\n", i, months[i]);
}
/* Done */
return 0;
}
SAMPLE OUTPUT:
Quote:
Enter next month, or "<Enter>" to exit: Jan
Enter next month, or "<Enter>" to exit: Feb
Enter next month, or "<Enter>" to exit: Mar
Enter next month, or "<Enter>" to exit:
End of data entry!
months[0]: Jan
months[1]: Feb
months[2]: Mar
i just wander , is there any way to do it using an array of pointers instead of a 2D array ??
No. Not really.
Because in C a string is an array of chars, an array of string is an array of arrays of chars.
Using other method's like with malloc() or calloc() you may not see this directly in code, but it does not in change the fact that strings are arrays of chars.
No. Not really.
Because in C a string is an array of chars, an array of string is an array of arrays of chars.
Using other method's like with malloc() or calloc() you may not see this directly in code, but it does not in change the fact that strings are arrays of chars.
No. That is not true. An array of arrays is very different from an array of pointers, even though the syntax for referencing an element is similar. In an array of arrays all the subarrays are consecutive (since it's an array). But in an array of pointers, the pointers can point to subarrays in random places in memory, without any order. In addition, the type signatures of an array of arrays is very different from an array of pointers (the former is a pointer to an array, the latter is a pointer to a pointer).
No. That is not true. An array of arrays is very different from an array of pointers, even though the syntax for referencing an element is similar. In an array of arrays all the subarrays are consecutive (since it's an array). But in an array of pointers, the pointers can point to subarrays in random places in memory, without any order. In addition, the type signatures of an array of arrays is very different from an array of pointers (the former is a pointer to an array, the latter is a pointer to a pointer).
True. You're right about that it's not an 2D arrays in terms of how it is stored in memory. Even though it is possible to write C code that demonstrates the difference, from a C code perspective there's no visible difference. Also keep in mind the OP is a beginner at C.
Distribution: Solaris 11.4, Oracle Linux, Mint, Debian/WSL
Posts: 9,789
Rep:
Quote:
Originally Posted by Hko
True. You're right about that it's not an 2D arrays in terms of how it is stored in memory. Even though it is possible to write C code that demonstrates the difference, from a C code perspective there's no visible difference. Also keep in mind the OP is a beginner at C.
Sorry about it but I disagree with the fact a beginner should be taught incorrect statements, especially in such a confusing area.
C pointers and arrays are sometimes similar, but are fundamentally differents in the way they are initialized, affected and stored, even from a C code perspective.
A C programmer has to know what kind of variables he is dealing with.
Code:
char a[8]; // array
char *p; // pointer
a="test"; // doesn't compile, 'a' cannot be affected, being immutable
strcpy(a,"test"); // OK, 'a' can (need to here) be overwritten
strcpy(p,"test"); // run time error, 'p' is uninitialized
p="test"; // 'p' must be affected, as it initially point to nothing sensible
printf("%s\n",a); // here 'a' and 'p' are used a similar way
printf("%s\n",p);
strcpy(p,"abcd"); // this may or may not work, depending on the compiler implementation and options used
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.